Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 583
matt Avatar asked Aug 04 '12 10:08

matt


2 Answers

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.

like image 109
adeneo Avatar answered Oct 04 '22 15:10

adeneo


If your event handler is bound to document, the event will have already been raised on the input element and bubbled up to the html element, so you will have to handle the exclusion within the code for the handler itself. The alternative is specifically binding a second handler for the input elements which prevents the event from bubbling, but that is probably not the right approach.

Code demo

$(function() {     $(document).keypress(function(e) {         if ($(e.target).is('input, textarea')) {             return;            }         if (e.which === 119) doSomething();     }); });​ 

p.s. you can have a look at the jQuery event object documentation to see what properties it exposes.

like image 28
nbrooks Avatar answered Oct 04 '22 14:10

nbrooks