Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!