Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable repetitive keydown in jQuery [duplicate]

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?

like image 842
Nazar Avatar asked Feb 01 '12 15:02

Nazar


2 Answers

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;
});
like image 132
Marc B Avatar answered Oct 04 '22 01:10

Marc B


keep a flag and turn it green upon keydown i would suggest keyup though

$(document).keydown(function(event){
     $flag=false;
     var keycode = (event.keyCode ? event.keyCode : event.which);

      if(keycode == '39'){
           if(!$flag){
              $flag=true;
              $("#box").animate({"left": "+=30px"}, "fast");
      }
     } 
   }); 
like image 38
Rafay Avatar answered Oct 04 '22 01:10

Rafay