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?

Answers:

Answer

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

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.