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?

Upvotes: 0

Views: 876

Answers (3)

GajendraSinghParihar
GajendraSinghParihar

Reputation: 9131

try this as your condition to return in the switch case

if(event.target.tagName != "INPUT" &&  event.target.tagName != "TEXTAREA" )
{
   return false;
   break;
  }

Upvotes: 0

Chris
Chris

Reputation: 726

This should work.. but you really shouldn't do this for accessiblity reasons.

var blockKeys = true; //Set this to true or false as needed
$(document).keydown(function(event) {
     switch(event.keyCode){
        case 37:
        case 39:
            if(blockKeys === true) {
                event.PreventDefault();
            }
            break;
     }
 });

Upvotes: 0

xdazz
xdazz

Reputation: 160923

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;
     }
 });

Upvotes: 2

Related Questions