How to prevent a "keypress" event firing a "click" event when focus is on a button - javascript/html dom

StackOverflow https://stackoverflow.com/questions/22151676

  •  19-10-2022
  •  | 
  •  

Question

I have a button that fires a "stopstart" function (animation). I also want to have a mouseless method to do this so I've bound the same function to the space bar. This works.

However if focus is on the button, and I press space - both events fire, can't work out how to stop this (the keypress event fires first - in chrome..)

Eventlistener code:

document.getElementById("stopstart").addEventListener("click",
        function (event) {
            stopstart();
        }); //add event listener to "stopstart" button  

document.addEventListener("keypress",
        function (event) {
            if (event.keyCode === 32) { //space key
                stopstart();
            }
        }); //add spacekey event listener to document

I don't want to remove focus from the button, as I'd like to retain that functionality - the two events appear to be separately generated - so I haven't found how to detect that the click event was in fact generated by the space bar.

Is this solvable using without having to add temporary flags to catch it etc

No correct solution

OTHER TIPS

The click location for key events is zero, zero so you can look for that.

document.getElementById("stopstart").addEventListener("click",
    function (event) {
        var x = event.x || event.clientX;
        var y = event.y || event.clientY;
        if (!x && !y) {
            alert("key press");
            return false;
        }
        stopstart();
    }); 

http://jsfiddle.net/mScEC/

     function (event) {
        if (event.pointerType !== "mouse") return;
         stopstart();
     }); //add event listener to "stopstart" button  

document.addEventListener("keypress",
     function (event) {
         if (event.keyCode === 32) { //space key
             stopstart();
         }
     }); //add spacekey event listener to document```

You can simply use event.preventDefault() inside keypress event Listener to prevent the Button Click event from getting triggered on keypress

e.g

document.addEventListener('keydown', function (e) {
    e.preventDefault();
    if (e.key === 'Enter') {
        try {
            // if expression is not evaluated then catch block will be executed
            screen.value = eval(screen.value);
        }
        catch (error) {
            console.log(error.message);
            screen.value = 'Invalid Operation';
        }
       
    }
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top