I'm pretty new to javascript and have been trying to figure out how to make an image move. I've come up with this code and it kind of works but the image stops moving after a little bit. How do I fix this?
<!DOCTYPE html>
<html>
<head>
<style>
#img {
position: relative;
}
</style>
<title>This is filler text</title>
</head>
<body>
<p>This is filler text</p>
<img src="example.jpeg" length="100" width="100" id="img" />
<script>
document.onkeydown = function(event) {
switch (event.keyCode) {
case 37:
moveLeft();
break;
case 38:
moveUp();
break;
case 39:
moveRight();
break;
case 40:
moveDown();
break;
}
};
function moveLeft() {
document.getElementById("img").style.left += "5px";
}
function moveRight(){
document.getElementById("img").style.right += "5px";
}
function moveDown(){
document.getElementById("img").style.bottom += "5px";
function moveUp(){
document.getElementById("img").style.top += "5px";
}
</script>
</body>
</html>
transform and translate instead of left / topconst EL_img = document.querySelector("#img");
const pos = {x:0, y:0};
document.addEventListener("keydown", (ev) => {
const dir = (ev.key.match(/(?<=^Arrow)\w+/)||[])[0];
if (!dir) return; // Not an arrow key.
ev.preventDefault(); // Prevent Browser scroll if overflow
({
Left: () => pos.x -= 5,
Right: () => pos.x += 5,
Up: () => pos.y -= 5,
Down: () => pos.y += 5,
}[dir])();
EL_img.style.transform = `translate(${pos.x}px, ${pos.y}px)`
});
#img {
height: 40px;
transition: transform 0.2s;
}
<img id=img height=40 src="https://lh3.googleusercontent.com/a-/AOh14Gh-CwvGkngFp6REJf46ncZD2p-nesp_4DmKOpSXGA=k-s420" />
Here's another similar answer
Several things that you'll need to change:
string values generally, so doing += "5px" will concatenate your strings after the first keypress.position for an element uses top / left / right / bottom as offsets from those respected edges. So for this demo, you'll probably only want to adjust left and right, with negative left values pushing it to the left and positive pushing it to the right. Similar for top.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`;
};
#img {
position: relative;
}
<p>This is filler text</p>
<img src="https://via.placeholder.com/100" length="100" width="100" id="img" />