1. Code
  2. Web Development

Quick Tip: Easy Sequential Animations in jQuery

Scroll to top
Read Time: 2 mins

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 jQuery

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!"


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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.