javascript - Continuous movement when a key is held down -
is possible in jquery have element continuously move when key held down?
i've tried few ways have break in between animation calls. code have:
$(document).keydown(function (e) { if (e.which == 37) { $('#you').stop().animate({ left: '-=16px' }, 10); } }); $(document).keyup(function (e) { $('#you').stop(); });
.animate()
isn't best way.
// cache jquery objects performance var = $( "#you" ) , doc = $( document ) // variable hold motion state , activemotion // godown motion, adjust numbers 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(); } // directions can go here in seperate if/else statements // sure include "activemotion !== godown" else every time // keydown event fires, start new godown loop. } ); doc.keyup( function () { // ends motion checked activemotion activemotion = null; } );
Comments
Post a Comment