How to stop all previous animations in jQuery before doing a new one?

I am just experimenting with jQuery.

I have an image that disappears into another image when mouseOver() happens and disappears on mouseOut()

It works great, except when you hover over the link again and again, say 5 times, the image disappears and disappears several times, 5 times, while you just sit there and wait for it to go with this crazy behavior.

To stop this behavior, I tried to use the flag and start the animation ONLY if it is no longer an animation, but guess what? If, say, I have 4 such buttons, and on each mouse button I have fadingIn another image, this animation will be ignored, since the flag is false.

So, is there a way to stop all previous animations before doing new ones? I am talking about the normal functions fadeIn() and slideDown() in jQuery


EDIT: Adding code from a link.

 <a href="javascript:void(0);" onMouseOver="mouseOverOut(false);" onMouseOut="mouseOverOut(true);">Tick</a> 

Javascript

 function mouseOverOut(t) { if(t) { $('.img1').fadeIn(); $('.img2').fadeOut(); } else { $('.img1').fadeOut(); $('.img2').fadeIn(); } } 
+7
jquery javascript-events
source share
3 answers

Using .stop() with fadeIn/Out can cause opacity to get stuck in a partial state.

One solution is to use .fadeTo() instead, which gives an absolute place for opacity.

 function mouseOverOut(t) { if(t) { $('.img1').stop().fadeTo(400, 1); $('.img2').stop().fadeTo(400, 0); } else { $('.img1').stop().fadeTo(400, 0); $('.img2').stop().fadeTo(400, 1); } } 

Here's a shorter way to record.

 function mouseOverOut(t) { $('.img1').stop().fadeTo(400, t ? 1 : 0); $('.img2').stop().fadeTo(400, t ? 0 : 1); } 

Or it might work. Check this out first.

 function mouseOverOut(t) { $('.img1').stop().fadeTo(400, t); $('.img2').stop().fadeTo(400, !t); } 

EDIT: This last one seems to work. True / false translates to 1/0. You can also use .animate() directly.

 function mouseOverOut(t) { $('.img1').stop().animate({opacity: t}); $('.img2').stop().animate({opacity: !t}); } 
+9
source share

Have you tried stop () yet ?

Description: Stop the current animation on matched elements.

+1
source share

using .stop()

+1
source share

All Articles