Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda