Restore default value of arrows key

516 Views Asked by At

I'm using a script (impress.js) that bins some particular action to keyup and keydown events for left, right, up and down arrows.

In some particular moments (for example while typing in a textarea) I want back the default behaviour for the arrows.

I tried without success with

$("a#show-ta").click( function() {      
  document.addEventListener("keydown", function ( event ) {
    if (event.keyCode >= 37 && event.keyCode <= 40) {
      return;
    }
  });
  document.addEventListener("keyup", function ( event ) {
    if (event.keyCode >= 37 && event.keyCode <= 40) {
      return;
    }
  }); 
}); 

where a#show-ta is the button that shows my textarea.

3

There are 3 best solutions below

1
On BEST ANSWER

You want to prevent the keypress from bubbling up to the document where (I assume) Impress binds its handlers:

$("textarea").on('keyup keydown keypress', function(e) {
  e.stopPropagation();
});
0
On

If you need the event in a specific zone, such as a texarea, you should stop the propagation of the event like this :

$('textarea').keydown( function(ev) {
    ev.stopPropagation();
});

If the events are necessary for the whole page but you want to exclude while you are in a textarea, for example, you could raise a flag which you would validate in the event.

var keydownActivated = true;

$('textarea').keydown( function(ev) {
    if (keydownActivated) {
        ev.preventDefault();
        // dostuff
    }
});
0
On

This will more or less get you where you are going. Create a flag that tracks whether or not the textarea has focus, and check that flag in your current key press event handlers. I can't see all of your code, so this is just a simple example:

var textareaHasFocus = false;

var textarea = document.querySelector('#yourTextarea');
textarea.addEventListener('focus', function(event) {
  textareaHasFocus = true;
}, false);

textarea.addEventListener('blur', function(event) {
  textareaHasFocus = false;
}, false);

document.addEventListener("keydown", function ( event ) {
  if (textareaHasFocus) return true;
  // your current keyboard handler
});
document.addEventListener("keyup", function ( event ) {
  if (textareaHasFocus) return true;
  // your current keyboard handler
});