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

96
Visualizações
Move HTML object with JavaScript while key is pressed

I'm writing a little game with vueJS as frontend. I managed to create all needed objects and now I want to make them move if a key is pressed.

My problem is I can only move them once every time the key is pressed. I want to move it consistently while the key is pressed.

My Code for moving is:

let myCircle = document.querySelector('.ball');
var key_left = false;

window.addEventListener('load', () =>{
    myCircle.style.position = 'absolute';
    myCircle.style.left = 0 + 'px';
    myCircle.style.top = 1200 + 'px';
});

window.addEventListener('keyup', (event) => {

if (event.key == 'ArrowLeft')
    key_left = true;

if (key_left == true)
{
    myCircle.style.left = parseInt(myCircle.style.left) - 5 + 'px';
}

When i tried to add a while loop it stoped moving at all.

Code:

let myCircle = document.querySelector('.ball');
var key_left = false;

window.addEventListener('load', () =>{
    myCircle.style.position = 'absolute';
    myCircle.style.left = 0 + 'px';
    myCircle.style.top = 1200 + 'px';
});

window.addEventListener('keyup', (event) => {

if (event.key == 'ArrowLeft')
    key_left = true;

while (key_left == true)
{
    myCircle.style.left = parseInt(myCircle.style.left) - 5 + 'px';
}

Someone has a hint for me?

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try to use the keydown event instead, it is fired every tick.

Or check out the examples at w3school. https://www.w3schools.com/jsref/event_onkeydown.asp

window.addEventListener('keydown', (event) => {
    myCircle.style.left = parseInt(myCircle.style.left) - 5 + 'px'
}
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