Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an image move with arrow keys with javascript?

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>
like image 774
OverripeBanana Avatar asked Nov 19 '25 07:11

OverripeBanana


1 Answers

  • Use CSS transform and translate instead of left / top
  • Use KeyboardEvent.key instead of the cryptic KeyboardEvent.keyCode

const 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

like image 114
Roko C. Buljan Avatar answered Nov 21 '25 20:11

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!