Search code examples
javascriptjqueryhtmlpreventdefault

Disable certain keys, but not for textarea and input


I've checked this wonderful websites database and somehow provided answers does not work.

To prevent glitches, by default I must disable arrow keys and spacebar. That works with this code:

window.addEventListener("keydown", function(e) {
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
        e.preventDefault();
    }
}, false);

But arrow keys and space bar are necessary for certain areas of website (input and textarea fields). To allow, I did as follows:

window.addEventListener("keydown", function(e) {
    if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) && ($(event.target)[0]!=$("textarea, input")[0])) {
        e.preventDefault();
    }
}, false);

But it does not seem to work. Help much appreciated!


Solution

  • In this case, one option you have is setting an event handler for all the textarea and input elements and utilizing event.stopPropagation() in order to prevent the window event handler from being fired. With this, the elements capture the keydown event and then tell the JavaScript engine not to fire other event handlers of elements that are higher in the DOM chain (such as the document or window).

    window.addEventListener("keydown", function(e) {
        if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1) {
            e.preventDefault();
        }
    }, false);
    

    And with jQuery:

    // Function gets run after document is loaded
    $(function(){
       $("textarea, input").keydown(function(e){
          e.stopPropagation()
       })
    });
    

    Edit: working jsFiddle.