Stop jQuery animations from backing up

February 14th, 2012 | by | coding, jquery

Feb
14

If you have ever developed something that used jQuery, then first off, good on you. I am all about jQuery over flash, flash is clucky, ugly, and most importantly not supported on mobile. If you haven’t heard, Android will stop their flash support, so quit your complaining.

Now on to the important part, if you ever run into the issue of jQuery animations that have to complete their mouseover and mouseout events before being able to repeat them. I am currently to lazy to code an example of this. But i will link to an example, and actually the article that helped me solve this issue the first time that I ran into this issue. So here is credit where credit is due Click Here for the Original Article.

But the quick fix is adding one simple function to your jQuery code. The stop() function works wonders. Here is the original code from my design portfolio Brewchee Design that made the three info blocks under the main image fade into the div background.

$("li:nth-child(1) .box div").mouseover(function () {
	$(this).fadeTo(500, 1);
});
$("li:nth-child(1) .box div").mouseout(function () {
	$(this).fadeTo(500, 0);
});
$("li:nth-child(2) .box div").mouseover(function () {
	$(this).fadeTo(500, 1);
});
$("li:nth-child(2) .box div").mouseout(function () {
	$(this).fadeTo(500, 0);
});
$("li:nth-child(3) .box div").mouseover(function () {
	$(this).fadeTo(500, 1);
});
$("li:nth-child(3) .box div").mouseout(function () {
	$(this).fadeTo(500, 0);
});

The above code cause some trouble, if you hovered over the div and and hovered out of the div very quickly, the animation would keep happening and keep building up a queue. Simply by adding the stop() function to the code above before the fadeTo function we fixed the queuing issue. Now this can be added to any jQuery function to stop this from happening.

$("li:nth-child(1) .box div").mouseover(function () {
	$(this).stop().fadeTo(500, 1);
});
$("li:nth-child(1) .box div").mouseout(function () {
	$(this).stop().fadeTo(500, 0);
});
$("li:nth-child(2) .box div").mouseover(function () {
	$(this).stop().fadeTo(500, 1);
});
$("li:nth-child(2) .box div").mouseout(function () {
	$(this).stop().fadeTo(500, 0);
});
$("li:nth-child(3) .box div").mouseover(function () {
	$(this).stop().fadeTo(500, 1);
});
$("li:nth-child(3) .box div").mouseout(function () {
	$(this).stop().fadeTo(500, 0);
});

Again I am not posting this to de-value the website that I mentioned above, this is purely to share my experience and use a reference for myself. So I wholeheartedly hope that this helps at lease one person, then I’ll be a happy person.

Authored by

Leave a Comment

Slidebox Demo for jeffbrutsche.com

Here is where you describe your awesome article!

Read More »