How to disable repetitive keydown in jQuery

Nazar picture Nazar · Feb 1, 2012 · Viewed 10.7k times · Source

When user keeps a key pressed, I want the keydown() event get called only once, but its called until user stops pressing the key.

Here is what I am trying to do:

   $(document).keydown(function(event){
     var keycode = (event.keyCode ? event.keyCode : event.which);
     if(keycode == '39'){
              $("#box").animate({"left": "+=30px"}, "fast");
     } 
   });  

So, when user presses right arrow key, I want the div#box to move 30px to the right. It moves but if user keeps key pressed it flies away.

I need it to move only by 30px per press, and stop, even if user keeps the key pressed. Do you know how it can be accomplished?

Answer

Marc B picture Marc B · Feb 1, 2012

Keep track of which keys are down, and ignore keycode 39 until a keyup even clears it:

var down = {};

$(document).keydown(function(event){
     var keycode = (event.keyCode ? event.keyCode : event.which);
     if(keycode == '39'){
          if (down['39'] == null) { // first press
              $("#box").animate({"left": "+=30px"}, "fast");
              down['39'] = true; // record that the key's down
          }
     } 
   });

$(document).keyup(function(event) {
     var keycode = (event.keyCode ? event.keyCode : event.which);
     down[keycode] = null;
});