Stephen Ostermiller Stephen Ostermiller - 4 months ago 14
jQuery Question

Binding arrow keys in jQuery except in input and textarea

I found this excellent question about binding the arrow keys with jQuery: Binding arrow keys in JS/jQuery with a great solution from Sygmoral:

$(document).keydown(function(e) {
switch(e.which) {
case 37: // left
break;

case 38: // up
break;

case 39: // right
break;

case 40: // down
break;

default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});


EXCEPT: This prevents the arrow keys from working the way they would usually work when the focus is in a text input field.

How would I modify this solution to allow the arrow keys to function normally when the current focus is in an input, text area, or another content editable area?

Jai Jai
Answer

Put this in a condition:

$(document).keydown(function(e) {
    if(!$(e.target).is(':input, [contenteditable]')){
        switch(e.which){
           // the cases as is
        }
        e.preventDefault(); // prevent the default action (scroll / move caret)
    }
});