50

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?

matt
  • 42,713
  • 103
  • 264
  • 397

4 Answers4

86

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.

adeneo
  • 312,895
  • 29
  • 395
  • 388
13

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.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
6

In jQuery, e.which is the normalized property, not e.keyCode.

To check if you are not in an input you can check the document.activeElement:

$(document).keypress(function(e) {
    if (e.which === 119 && !$(document.activeElement).is(":input,[contenteditable]")) {
        doSomething();
    }
});

Demo. http://jsfiddle.net/pxCS2/1/

Esailija
  • 138,174
  • 23
  • 272
  • 326
2

The easiest and perfect solution is:

$(document).keypress(function(e) {
    if (e.which == 119 && !$(':focus').length) {
        doSomething();
    }
});
Buzogany Laszlo
  • 921
  • 11
  • 19
  • 1
    As your code is currently written, it filters too much. Anchors by default can get focus. Also, anything with a tabindex. So, this isn't the best solution for handling keyboard shortcuts on a web page where the keyboard may be used to navigate around the web page. http://jsfiddle.net/wiredprairie/pp9e9/ – WiredPrairie Mar 20 '13 at 22:05