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

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

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 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