Several things that you'll need to change:
- Inline styles are going to return
stringvalues generally, so doing+= "5px"will concatenate your strings after the first keypress. positionfor an element usestop / left / right / bottomas offsets from those respected edges. So for this demo, you'll probably only want to adjustleftandright, with negativeleftvalues pushing it to the left and positive pushing it to the right. Similar fortop.
Because of these two, it'll probably be easier to have some separate Number variables for these offsets, operate on those variables directly, then update your inline style.
Here is an example of that:
let left_offset = 0;
let top_offset = 0;
document.onkeydown = function (event) {
let img = document.getElementById("img");
switch (event.keyCode) {
case 37:
// Move left
left_offset -= 5;
break;
case 38:
// Move up
top_offset -= 5;
break;
case 39:
// Move right
left_offset += 5;
break;
case 40:
// Move down
top_offset += 5;
break;
}
img.style.left = `${left_offset}px`;
img.style.top = `${top_offset}px`;
};