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?
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";
}
<body>
<p>This is filler text</p>
<img src="https://via.placeholder.com/100" length="100" width="100" id="img" />
</body>
transform and translate instead of left / topconst elImg = document.querySelector("#img");
const pos = { x: 0, y: 0 };
const move = (x) => elImg.style.translate = `${pos.x}px ${pos.y}px`;
const keyActions = {
ArrowLeft: () => move(pos.x -= 40),
ArrowRight: () => move(pos.x += 40),
};
addEventListener("keydown", (evt) => {
evt.preventDefault();
if (!evt.repeat) keyActions[evt.key]?.();
});
#img {
transition: translate 0.3s;
}
<p>Use arrows left, right</p>
<img id="img" src="https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico" />
Here's another similar answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With