Home > Mobile >  Move HTML object with JavaScript while key is pressed
Move HTML object with JavaScript while key is pressed

Time:06-23

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!

CodePudding user response:

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'
}
  • Related