Home > database >  Spacebar Event Listener stops after button press
Spacebar Event Listener stops after button press

Time:07-08

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pew Pew</title>
  </head>
  <body>
        <canvas id="gameCanvas" height="800px" width="1000px"></canvas>
        <div >
        <button id="atkUp" onclick="player.attackSpeedUp()">1 Atk Speed - 1c</button>
        <button id="dmgUp" onclick="player.damageUp()">1 Damage - 1c</button>
        <button id="multishotUp" onClick="player.multishotUp()">1 Multi-Shot - 1c</button>
        <button id="moveSpeedUp" onClick="player.moveSpeedUp()">1 Move Speed - 1c</button>
        <button id="armorUp" onclick="player.armorUp()">1 Armor - 1c</button>
         <p>UPGRADES</p>
        </div>
  </body>
</html>
document.addEventListener("keypress", (event) =>{
    if(event.keyCode == 32){
        player.shoot();
    }
}, false);

My problem is that when I click on any of my upgrade buttons (any button within .button-div), when I press the space key it activates ('clicks') the last button I pressed and does NOT fire my eventlistener. Is there a way to programmatically un-focus the most recent button and/or stop the button from robbing me of my space bar input.

CodePudding user response:

Try this, the problem was that when you click a button you focus on this button, and the space bar triggers a trick on the button that yout are focused. I added some code to remove focus, to blur all buttons when you press the spacebar:

    function deselectAllUpgradeButtons() {
        for (const element of document.querySelector('.button-div').children) {
            element.blur();
        }
    }

    document.addEventListener(
        'keypress',
        (event) => {
            if (event.keyCode == 32) {
                deselectAllUpgradeButtons();
                player.shoot();
            }
        },
        false
    );

CodePudding user response:

Try this:

    document.body.onkeyup = function(event){
    event.preventDefault()
    if(event.keyCode === 32){
        player.shoot();
    }
  };
  • Related