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

138
Views
How to consider an second event when only the first one happens?

I am trying to use keyboard events, but I just can do it using the first event, in this case, key-down, but when I try key-up nothing happens.

const box = document.createElement("div")
box.setAttribute("id", "box")
document.querySelector("body").appendChild(box)

let boxTop = 20;
let boxLeft = 20;

document.addEventListener("keydown", (e) => {
    let keyName = e.key
    if(keyName === "ArrowDown") {
        box.style.top = boxTop + "10px"
    }
})

document.addEventListener("keyup", (e) => {
    let keyName = e.key
    if(keyName === "ArrowUp") {
        box.style.top = boxTop - "10px"
    }
})
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You need position absolute and you need to use

(boxTop + 10)+"px"
(boxTop - 10)+"px"

Change plus and minus to

+= and -= if you want to continue to move

Perhaps test you are at top?

Why not use keyDown on both event handlers?

const box = document.createElement("div")
box.setAttribute("id", "box")
document.querySelector("body").appendChild(box)

let boxTop = 20;
let boxLeft = 20;

document.addEventListener("keydown", (e) => {
  let keyName = e.key
  if (keyName === "ArrowDown") {
    box.style.top = (boxTop += 10)+"px"
  }
})

document.addEventListener("keyup", (e) => {
  let keyName = e.key
  if (keyName === "ArrowUp") {
    let  top = (boxTop -= 10);
    if (top<0) top = 0; // unleess you want them to move out of viewport
    box.style.top = top+"px"
  }
})
div { border: 1px solid black; height: 100px; width:100px;  position: absolute;  }

about 4 years ago · Juan Pablo Isaza Report

0

The event happened. There is no change because of this.

box.style.top = boxTop - "10px"
box.style.top = boxTop + "10px"

Please change it.

box.style.top = boxTop - 10 + "px"
box.style.top = boxTop + 10 + "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!