Prevent the spacebar from starting any other buttons in jQuery

I have an application where I use the spacebar to switch functions anywhere in the window. However, if any other button or flag has focus, then it is also clicked.

I tried to do warnDefault (), but this did not work as expected. How can I guarantee that no other item on the screen will be pressed when I press the spacebar?

HTML

<button class="buttons" id="playBtn">PLAY</button>

JS (updated to use the default prevent command to go to space

$(document).keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);

    if(keycode == '32') {
        if (event.stopPropagation) {
            event.stopPropagation();
            event.preventDefault();
        }
        playBtn_DOM.click();
    } else if (keycode == '97') {
        event.preventDefault();
        prevBtn_DOM.click();
    } else if (keycode == '100') {
        event.preventDefault();
        nextBtn_DOM.click();
    }
});

As for the answer. When using the default prevention function to capture a space, this solution did not work. I updated the JS code to show that I was trying to include the solution provided there.

+5
5

. !

$(document).mousemove(function(event){
    if (document.activeElement != document.body) document.activeElement.blur();
 });

, , - . , , .

0

, , keyup . , : https://jsfiddle.net/Beppe/o6gfertu/1/. Firefox Chrome, , .

+4

$(element).blur();

(, ), (, click ).

+2
source

This will remove focus from all buttons as soon as they are focused (for example, by clicking). This will prevent the space from ever activating the buttons.

document.querySelectorAll("button").forEach( function(item) {
    item.addEventListener('focus', function() {
        this.blur();
    })
})
+2
source

For those who expect a space in some text input in an interactive DIV. Try it:

HTML:

<div id="someClickableDiv" onclick="doSomething()">
    <textarea onkeyup="event.preventDefault()"></textarea>
</div>

Or version of Angular 6:

<div id="someClickableDiv" (click)"doSomething()">
    <textarea (keyup)="$event.preventDefault()"></textarea>
</div>
0
source

Source: https://habr.com/ru/post/1530810/


All Articles