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

143
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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