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

255
Visualizações
addEventListener only works when I use window infront of it

I would like to use a code when I press the space bar a shape appears and it disappears when I press it again. I'm trying to get the addEventListener to work with a sample:

hello = document.querySelector('#Player');

with player being the id of the shape that I want to control. I declared hello above and initialized it in setup (I am using JavaScript), the Player id has also been initialized in HTML and given a shape in CSS. When I use

hello.addEventListener('keypress', (event) => {
  console.log(event.key)
})

nothing happens, but when I use

window.addEventListener('keypress', (event) => {
  console.log(event.key)
})

it works. Is there anything that I am doing wrong?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

That's what should happen.

You can add the keypress event to the window or document.

And, if you add it to both, the window wins over for some reason – someone else might clarify this to both of us.

const el = document.getElementById("el");
el.addEventListener("keypress", event => keyPressed(event, "blue"));
document.addEventListener("keypress", event => keyPressed(event, "green"));
window.addEventListener("keypress", event => keyPressed(event, "purple"));
function keyPressed(event, color) {
    if (event.key = " ")
        el.style.backgroundColor = color;
}
#el {
  width: 100px;
  height: 100px;
  background: red;
}
<div id="el"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

It is because by default div is not selectable. In order to make it selectable you need to use tabindex attribute on your div. It will make your div selectable.

const hello = document.querySelector('#player');

hello.addEventListener("keypress", evt => {
  console.log(evt.key)
})
<div id="player" tabindex="0">
  Player Shape
</div>

It will show a boundary around your div which can be remove by using css -

outline: none;
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