Quick Tip: Prevent Animation Queue Buildup

You've probably stumbled upon a navigation powered by some jQuery effects during your web adventures. Of course you then ran your mouse back and forth over the navigation really fast to watch the animation repeat itself over and over and over again.

The natural queuing of animations/effects by jQuery makes the typical animation super easy to code and move on to more important tasks. However, sometimes the animation queue just gets in the way.

Here is an example of a navigation that has some effects applied to it via jQuery. Mouse back and forth over the links to see how the animations build up.

Here is the JavaScript that does the effect for the menu:

[js]$(document).ready(function() { $('ul.anim_queue_example1 a') .hover(function() { $(this).animate({ left: 20 }, 'fast'); }, function() { $(this).animate({ left: 0 }, 'fast'); }); });[/js]

Now let's look at how we can prevent this undesirable behavior. Ready? Simply call the .stop() method before animating again. Here is the updated JavaScript that fixes the animation queue buildup by using the .stop() method.

[js]$(document).ready(function() { $('ul.anim_queue_example2 a') .hover(function() { $(this).stop().animate({ left: 20 }, 'fast'); }, function() { $(this).stop().animate({ left: 0 }, 'fast'); }); });[/js]

Here is the navigation again, using the above JavaScript.

As you can see, the animation is no longer queued up by moving your mouse back and forth over the menu items.

You can even get bonus points for implementing something like the hoverIntent plugin that can add a slight delay before running the animation. Doing so makes sure the animation plays only if the user actually places the mouse on the element.

For more information about the .stop() method, visit the jQuery documentation page. To see a real-world example of the .stop() method in action, using its two arguments — clearQueue and goToEnd — check out the script Karl Swedberg put together at Little Orange Star.

Update: This article has been translated into Belorussian.



Responsive Menu
Add more content here...