jQuery: trigger keypress function on entire document but not inside inputs and textareas?

matt picture matt · Aug 4, 2012 · Viewed 54.2k times · Source

I have this …

$(document).keypress(function(e) {
        if ( e.keyCode === 119 ) // w
            doSomething();
    });

Wo when pressing "w" on my document the doSomething() function fires. How can I prevent it from firing when I'm currently typing (in focus) in an input field or textarea?

Answer

adeneo picture adeneo · Aug 4, 2012

You'll have to filter out the elements after the event and not in the selector, like this

$(document).on('keypress', function(e) {
    var tag = e.target.tagName.toLowerCase();
    if ( e.which === 119 && tag != 'input' && tag != 'textarea') 
        doSomething();
});

this checks the tagname of the event.target, the element the event originated from, and only fires the function if the event did not originate from an input or textarea.