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

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

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 Report

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