js noob
js noob

Reputation: 77

Exclude keypress from certain element

I want to catch spacebar and below did catch it. However it's tied to document, the catch will trigger even if I press spacebar when I'm typing in an input box. How to exclude that?

$(document).keypress(function(e) {
    if(e.which == 32) {
        alert('trigger');
    }
});

Upvotes: 1

Views: 71

Answers (1)

MorKadosh
MorKadosh

Reputation: 6006

You can use nodeName to catch the event source: http://jsfiddle.net/t8jqb2rq/

//Array of sources you want to include
var includeIn = ['BODY','TEXTAREA'];
$(document).keypress(function(e) {
    if(e.which == 32 && includeIn.indexOf(e.target.nodeName) != -1) {
        alert('trigger');
    }

 });

Upvotes: 1

Related Questions