Avoid Multiple hover() Animations in Parallel - J Query

We all have fallen for this at least once. You set up something like this:

For example, you could be enlarging an element each time the mouse rolls over it and then shrinking it to its initial size once the mouse rolls out.
All goes well until you quickly move the mouse over and out of the element and...what?!
The jQuery('#something') element suddenly gets resized back and forth many times until it finally stops.


The solution is indeed simple, too simple, but the problem is so recurrent that I really consider this solution a useful one.
What you need to do in order to avoid this nasty effect is simply kill all existing animations on the element before you create a new one.
To do so, you have to use jQuery’s stop() method. It will (as the name says) stop the current animation and, optionally, remove the following ones as well.



I’ll show you an example of animating the opacity CSS property, but it works the same for any other property:

Not there yet

There’s still another related problem that could arise in a situation like this:

If you try this code and move the mouse quickly, the element will get animated crazily again, but only its height (not the opacity) will animate.
The reason is simple; jQuery animations get queued by default. This means that if you add several animations, they’ll get executed in sequence.
stop() by default only stops (and removes) the current animation. In our last example, only the opacity animation will be removed each time, leaving the height animation in the queue, ready to run.
To work around this, you have to either call stop() one more time or pass true as the first argument. This will make stop() clean all the queued animations as well. Our hover code should look like this:

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics