Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

    returnthis; // 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();

Solution 2:

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

Solution 3:

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

functiongrow_anim() {
  if (over) {
    $(swinger).animate({left: "5px"}, 200, 'linear', shrink_anim);
  }
}

functionshrink_anim() {
  $(swinger).animate({left: "0"}, 200, 'linear', grow_anim);
}

Solution 4:

Consider:

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

with:

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

and:

var over = false;
$(function() {
  $("#anim").hover(function() {
    over = true;
    grow_anim();
  }, function() {
    over = false;
  });
});

functiongrow_anim() {
  if (over) {
    $("#anim").animate({paddingLeft: "100px"}, 1000, shrink_anim);
  }
}

functionshrink_anim() {
  $("#anim").animate({paddingLeft: "15px"}, 1000, grow_anim);
}

You can achieve this using timers too.

Post a Comment for "Jquery Continuous Animation On Mouseover"