Quick Tip: Easy Sequential Animations in jQuery

Quick Tip: Easy Sequential Animations in jQuery

In this video quick tip, I’ll demonstrate an easy way to allow for sequential animations of an infinite number of elements. I originally learned this technique from Dave Methvin, but don’t think that many people are aware of this neat little trick.


The Goal

We want to filter through an infinite number of elements on a page, matching some selector, and then make them sequentially fade out.

The HTML

<body>
  <p>Watch</p>
  <p>Me</p>
  <p>Disappear</p>
</body>

The jQuery

var paras = $('p'),
    i = 0;

// If using jQuery 1.4, you don't need to do || [].
(function() {
  $(paras[i++] || []).fadeOut('slow', arguments.callee);
})();

We begin by “caching” all of the paragraphs on the page, wrapped in the jQuery object (var paras). We also create an iterator variable – i. This iterator will allows us to target each new paragraph element, without knowing the specific length of the paras object ahead of time.

Within the self-invoking anonymous function, we get the first paragraph on the page with “paras[i]” … But we want to increment i by one for each iteration. This way, the next time the selection is called, it’ll be referring to the next element in the wrapped set. So, we must be sure to write paras[i++]. Then, it’s a simple matter of calling fadeout, and passing arguments.callee as the callback function, to allow for recursion. This will be equal to the function it’s contained in; so we’re essentially saying “rinse and repeat!”

alert(arguments.callee); // alerts the following

 (function() {
  $(paras[i++] || []).fadeOut('slow', arguments.callee);
})();

Note

If, for some reason, you’re using jQuery 1.3 or older, you need to specify what should happen when paras[i] is equal to an element that doesn’t exist. In older versions of jQuery, it returns an error, “undefined.” To compensate, we pass $(paras[i++] || []) to specify that, if the element doesn’t exist, we instead wrap an empty array, to avoid any errors.

It should be noted that, as of jQuery 1.4, this is unnecessary, as jQuery will return the jQuery object instead.



Leave a Reply

Your email address will not be published. Required fields are marked *