JavaScript key listener disabled when inside a text form

javascript, jquery, jquery-events, jquery-ui

Solution

First, there's no need for the browser check. For checking arrow keys, just use the `keydown` event for all keys.

Second, I suggest (as Sean Hogan did) checking the target of the event before doing the slideshow stuff. The following will work on all mainstream desktop browsers:

document.body.onkeydown = function(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    var targetTagName = (target.nodeType == 1) ? target.nodeName.toUpperCase() : "";
    if ( !/INPUT|SELECT|TEXTAREA/.test(targetTagName) ) { 
        switch (evt.keyCode) {
            case 37:
                changeImage('prev');
                break;
            case 39:
                changeImage('next');
                break;
        }
    }
}

Problem

I have a key listener assigned to the arrow keys to navigate a slideshow. But I want to disable the key listener, temporarily, while a user is typing inside an input field. How can I do that? My current code looks like this: ``` //Listen to the keys function checkKey(e) { switch (e.keyCode) { case 37: changeImage('prev'); break; case 39: changeImage('next');; break; } } if (jQuery.browser.mozilla) { jQuery(document).keypress (checkKey); } else { jQuery(document).keydown (checkKey); } ```

Original source