Tuesday 28 December 2010

Repeat jQuery animation

As I've said in previous posts, jQuery is a really lovely tool, mainly for DOM manipulation and animation. It makes really simple to add animations to different items, like menus, pop up "pseudo windows" (divs), items to be shown-hidden...

Over the time, some people have started to use it as a replacement for the typical, so frequent (years ago) flash intros or flash banners. There's something missing, though, a way to keep the same animation going over and over (imagine for example the typical matrix like binary cascade).
Well, it's pretty easy to chain animations by adding a callback to jQuery's animate method, so using this functionality to write something that would keep chaining one animation to another over and over turns out to be rather simple.

I've created a simple "class" animationsRepeater that just needs a target jQuery element to be animated, an array of animationInfo's "structs" (each animationInfo is just the same object that jQuery's animate method expects), and the number of times that I want to repeat this sequence of animationInfo's over the target object (-1 means repeat forever). Aside from the obvious run() method, I've added a pause() one.

Usage is that simple as this:


var animRepeater = new animationsRepeater($("#myItem),
[new animationInfo({left: "+=400", opacity: 0.25}, 2000, false),
new animationInfo({left: "-=400", opacity: 1}, 2000, false)],
-1);
animRepeater.run();



the code above means, move "#myItem" to the left 400 pixels and change its opacity to 0.25, and do it in 2000 milliseconds. Then, move "#myItem" to the left -400pixels (so, move it to the right) and change its opacity to 1, and do it in 2000 milliseconds. The last -1 means we want to apply these 2 animations indefinitely.

You can view a sample with several squares moving here. The code there creates 5 divs and instantiates a different animationsRepeater for each of them, with slightly different values. Each animation repeater applies a move right and decrease opacity animation first, followed by a move left and increase opacity animation then. This cycle of animation repeats indefinitely.

The animationsRepeater class is here. I think the most (and only) interesting thing there is how what should be a normal loop (do animation from 1 to n times) has been transformed in a timed pseudo-recursive (it's not really recursive cause the timer thing means the previous function call is more than finished when it gets called again) call. _doAnimation calls to jQuery's animate, passing to it as callback parameter the same _doAnimation function, so we can think of the code in _doAnimation as the code that would be inside a loop and the associated loop conditions.

No comments:

Post a Comment