Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda