Tuesday, December 15, 2009

Quick Tip: Prevent Animation Queue Buildup

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:
JavaScript:
  1. $(document).ready(function() {
  2. $('ul.anim_queue_example1 a')
  3. .hover(function() {
  4. $(this).animate({ left: 20 }, 'fast');
  5. }, function() {
  6. $(this).animate({ left: 0 }, 'fast');
  7. });
  8. });
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.
JavaScript:
  1. $(document).ready(function() {
  2. $('ul.anim_queue_example2 a')
  3. .hover(function() {
  4. $(this).stop().animate({ left: 20 }, 'fast');
  5. }, function() {
  6. $(this).stop().animate({ left: 0 }, 'fast');
  7. });
  8. });
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.