Leo Jiang
Leo Jiang

Reputation: 26223

Stop .hover animation when the mouse leaves in JQuery

I have something like:

$('.test').hover(
 function(){
  $(this).animate(...);
 }, function(){
  $(this).animate(...);
 }
);

But if the user's mouse leaves before the animation finishes, the animations continue. If I quickly hover and unhover the element quickly and repeatedly, the animations repeat several times after the mouse left the element. How can I make the animations stop after the mouse left the element?

Upvotes: 4

Views: 4346

Answers (1)

Kip
Kip

Reputation: 109503

You're looking for stop():

$('.test').hover(
 function(){
  $(this).stop(true).animate(...);
 }, function(){
  $(this).stop(true).animate(...);
 }
);

There are two optional boolean parameters. The first is clearQueue. If set to false (or omitted), it is more like pausing the animation than stopping it. The next time you start an animation on that object it will finish the paused animation, and any other queued up animations, before continuing. In your case you want it to be true, which will tell it to actually stop the animation and clear any queued actions.

The second optional parameter is jumpToEnd. If false (or omitted), the animation is stopped in its tracks. If true, it will jump to the state the object is in at the end of the animation. You probably want to leave this one out, though it depends on what types of animations you're doing.

For example, suppose you are fading from 0% opacity to 100% opacity, and you are at 75% opacity when you call stop(), then you call a fade to 0% opacity. Without clearQueue, the object will continue fading to 100% and then fade back to 0%. With clearQueue, the object will stop fading at 75% then immediately start fading back to 0%. If jumpToEnd is true, the object would immediately change from 75% to 100% opacity before fading back to 0%.

Upvotes: 6

Related Questions