Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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?

<!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>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

const 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

about 4 years ago · Juan Pablo Isaza Report

0

Several things that you'll need to change:

  • Inline styles are going to return 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" />

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!