Continuous movement while holding a key

Is it possible that in jQuery an element constantly moves while holding down a key?

I tried several ways, but they always have a gap between animation calls. The code I have is:

$(document).keydown(function (e) {
    if (e.which == 37) {
        $('#you').stop().animate({
            left: '-=16px'
        }, 10);
    }
});
$(document).keyup(function (e) {
    $('#you').stop();
});
+5
source share
3 answers

.animate() not always the best way.

// cache jQuery objects for performance
var you = $( "#you" )
, doc = $( document )

// variable to hold motion state
, activeMotion

// goDown motion, adjust numbers to taste
, goDown = function(){
   you.css( "left" , you.css( "left" ) - 16 );
   if ( activeMotion === goDown ) {
      setTimeout( goDown , 10 );
   }
}

doc.keydown( function( e ) {
   if ( e.which === 37 && activeMotion !== goDown ) {
      activeMotion = goDown;
      goDown();
   }
   // all directions can go here in seperate if/else statements
   // be sure to include "activeMotion !== goDown" else every time
   // keydown event fires, it will start a new goDown loop.
} );

doc.keyup( function () {
   // simply ends any motion that checked activeMotion
   activeMotion = null;
} );
+3
source

Instead of animating an element, rather just move it a certain number of pixels. 16 is likely to be too much because it will be too fast.

0
source

, - .

If you look at the repetition interval of the operating system keyboard, it should be about 35 milliseconds - test it here .

In addition, you animate every 10 ms, not counting the time required to run all the animation functions, etc. So why not simplify the animation and not worry about time intervals ( try this demo ):

var block = $('.block'),
    leftPos;
$(document).keydown(function (e) {
    leftPos = block.position().left;
    leftPos += (e.which == 37) ? -5 : 0;
    leftPos += (e.which == 39) ? 5 : 0;
    block.css('left', leftPos);
});
0
source

All Articles