Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery continuous animation on mouseover

I am trying to have an animation run only when the mouse is over an object. I can get one iteration of the animation and then have it set back to normal on mouse out. But I'd like the animation to loop on mouseover. How would I do it, using setInterval? I'm a little stuck.

like image 438
V_H Avatar asked Jan 11 '10 03:01

V_H


3 Answers

It could be done like this:

$.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 wanted the animation immediately stop, you could change the hoverOut line to read:

$(this).data('loop', false).stop();
like image 197
Doug Neiner Avatar answered Oct 23 '22 18:10

Doug Neiner


setInterval returns an id 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); }
);
like image 4
SLaks Avatar answered Oct 23 '22 16:10

SLaks


I needed this to work for more then one object on the page so I modified a little Cletus's code :

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);
}
like image 4
tsi Avatar answered Oct 23 '22 16:10

tsi