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

231
Views
When pressing on spacebar the previous clicked button gets clicked

I'm building a game that throws bombs when pressing the spacebar and the problem is that when I press this key the game ends, because it interprets pressing the spacebar to click the previously clicked button Start Game which changes to End Game once the game starts.

How can I solve this issue? Here is an example of what I mean:

var spacebar = false, btn = document.getElementById('btn');

btn.addEventListener('click', () => { console.log('test') })

// ---- Spacebar functionality ----
function handleKeyDown(e){
  e.keyCode === 32 ? spacebar = true : null
}
function handleKeyUp(e){
  e.keyCode === 32 ? spacebar = false : null
}
document.addEventListener("keydown", handleKeyDown, false)
document.addEventListener("keyup", handleKeyUp, false)
1) Click the button
<br>
2) Now without clicking press the spacebar
<br><br>
<button id="btn">Click me to console log</button>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Try with document.activeElement.blur(); and lost the focus on the button.

var spacebar = false, btn = document.getElementById('btn');

btn.addEventListener('click', () => { 
  console.log('test');

  document.activeElement.blur(); //<----- Here my edit

})

// ---- Spacebar functionality ----
function handleKeyDown(e){
  e.keyCode === 32 ? spacebar = true : null
}
function handleKeyUp(e){
  e.keyCode === 32 ? spacebar = false : null
}
document.addEventListener("keydown", handleKeyDown, false)
document.addEventListener("keyup", handleKeyUp, false)
1) Click the button
<br>
2) Now without clicking press the spacebar
<br><br>
<button id="btn">Click me to console log</button>

about 4 years ago · Juan Pablo Isaza Report

0

You can do it by removing button response to the 'keyup' event

<button id="btn" onkeyup="event.preventDefault()">Click me to console log</button>
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!