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>
CodePudding user response:
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>
CodePudding user response:
You can do it by removing button response to the 'keyup' event
<button id="btn" onkeyup="event.preventDefault()">Click me to console log</button>
