Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda