简体   繁体   中英

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

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

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

eg

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';
        }
       
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM