Using default prevention to accept a space

I have code like this that uses the space function:

    $(document).keypress(function (e) { 
        e.preventDefault();                            
        if (e.which == 32) {
            // func
        }
    }); 

Unfortunately, this destroys all standard defaults.

It:

    $(document).keypress(function (e) { 
        if (e.which == 32) {
            e.preventDefault();
            // func
        }
    }); 

Unfortunately, inefficient.

How can I make this preventDefault just a space?

Thank.

+1
source share
4 answers

Try the following:

//e= e || window.event); you may need this statement to make sure IE doesn't keep the orginal event in motion
var code;  
if (e.keyCode) {
 code = e.keyCode;
} else if (e.which) {
 code = e.which;
 }
if (code == 32) {
 if (e.stopPropagation) {
 e.stopPropagation();
 e.preventDefault();
 }
 return false;
}
+2
source

For some of the above, such as using $, it can be a bit confusing. So I am posting my answer with javascript code. Add this to any file to block the space (or you can also add other actions).

window.onkeydown = function (event) {
    if (event.keyCode === 32) {
        event.preventDefault();
    }
};

Keycode 32 is a space. For other key codes check this site:

http://www.javascripter.net/faq/keycodes.htm

.

+1

?

, switch() if-then-else?

0

Try

$(document).keydown(function(e){
if(e.which==32) e.preventDefault();
});

I use it to lock the Esc key and works great for me.

-1
source

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


All Articles