undefined undefined - 8 days ago 6
Javascript Question

SOLVED - jQuery - Disable keydown in input and textareas

I am using the arrow keys (and A,W,D) to navigate between pages.

How can I disable the keydown function for textareas and inputfields?

   $(document).keydown(function(e) {
switch(e.which) {
case 65:
leftArrowPressed();
break;
case 37:
leftArrowPressed();
break;
case 68:
rightArrowPressed();
break;
case 39:
rightArrowPressed();
break;
case 72:
homePressed();
break;
case 87:
homePressed();
break;
}
});

Answer

You could use this (needs Internet Explorer 9+):

function leftArrowPressed() { console.log('left pressed'); }
function rightArrowPressed() { console.log('right pressed'); }
function homePressed() { console.log('home pressed'); }

$(document).keydown(function(e) {
    var el = document.activeElement;
    try {
        if (el && el.selectionStart !== undefined || el.isContentEditable) {
            console.log('skip');
            return; // active element has caret, do not proceed
        }
    } catch (ex) {}
    var f = {
        65: leftArrowPressed,
        37: leftArrowPressed,
        68: rightArrowPressed,
        39: rightArrowPressed,
        72: homePressed,
        87: homePressed
    };
    if (f[e.which]) f[e.which]();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="test">
<input type="checkbox">
<textarea>test
</textarea>
<div contenteditable>test</div>