Continuous jQuery mouseover

I try to start the animation only when the mouse is over an object. I can get one iteration of the animation, and then return it to normal operation. But I would like the animation to loop on the mouse. How do I do this using setInterval? I'm a little stuck.

+6
javascript jquery animation mouseover
source share
4 answers

This can be done as follows:

$.fn.loopingAnimation = function(props, dur, eas) { if (this.data('loop') == true) { this.animate( props, dur, eas, function() { if( $(this).data('loop') == true ) $(this).loopingAnimation(props, dur, eas); }); } return this; // Don't break the chain } 

Now you can do this:

 $("div.animate").hover(function(){ $(this).data('loop', true).stop().loopingAnimation({ left: "+10px"}, 300); }, function(){ $(this).data('loop', false); // Now our animation will stop after fully completing its last cycle }); 

If you want the animation to stop immediately, you can change the hoverOut line to read:

 $(this).data('loop', false).stop(); 
+9
source share

setInterval returns an identifier that can be passed to clearInterval to disable the timer.

You can write the following:

 var timerId; $(something).hover( function() { timerId = setInterval(function() { ... }, 100); }, function() { clearInterval(timerId); } ); 
+4
source share

I need this to work for more than one object per page, so I changed the Cletus code a bit:

 var over = false; $(function() { $("#hovered-item").hover(function() { $(this).css("position", "relative"); over = true; swinger = this; grow_anim(); }, function() { over = false; }); }); function grow_anim() { if (over) { $(swinger).animate({left: "5px"}, 200, 'linear', shrink_anim); } } function shrink_anim() { $(swinger).animate({left: "0"}, 200, 'linear', grow_anim); } 
+4
source share

Consider:

 <div id="anim">This is a test</div> 

from:

 #anim { padding: 15px; background: yellow; } 

and

 var over = false; $(function() { $("#anim").hover(function() { over = true; grow_anim(); }, function() { over = false; }); }); function grow_anim() { if (over) { $("#anim").animate({paddingLeft: "100px"}, 1000, shrink_anim); } } function shrink_anim() { $("#anim").animate({paddingLeft: "15px"}, 1000, grow_anim); } 

You can achieve this with the help of timers.

+1
source share

All Articles