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

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

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

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