Search code examples
jquerytextareaonfocus

Activating and deactivating arrow keys with jquery


I am deactivating the left and right arrow keys when the page is loaded with the following:

$(document).keydown(function(event) {
     switch(event.keyCode){
        case 37:
        case 39:
            return false;
            break;
     }
 });

I want to reactivate them when the textarea or a input field id onfocus, and deactivate them again when that element is not in focus anymore. How would you do that?


Solution

  • You could check the event.target.

    $(document).keydown(function(event) {
        if (event.target instanceof HTMLInputElement 
         || event.target instanceof HTMLTextAreaElement)     { 
           return true;
        }
         switch(event.keyCode){
            case 37:
            case 39:
                return false;
                break;
         }
     });