July 2nd, 2012
The jQuery animation API provides a way to control almost any CSS property such as position, opacity, color, font size, and more.
One of the most overlooked parameters is the step function.
The step function is a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. This gives you the possibility to control every frame of the animation, allowing almost limitless power to do whatever you want with it.
Take a closer look at the following example:
$("div.progress").animate({ 'width': 450 }, { duration: 3000, step: function(now, fx) { if (fx.pos < 0.25) { $(this).css("background-color", "red"); } else if (fx.pos > 0.25 && fx.pos < 0.5) { $(this).css("background-color", "yellow"); } else if (fx.pos > 0.5 && fx.pos < 0.75) { $(this).css("background-color", "orange"); } else if (fx.pos > 0.75) { $(this).css("background-color", "green"); } if (fx.pos != 1) { $("span").text((fx.pos * 100).toFixed(0) + "%"); } else { $("span").text("Done!"); } } });
At first, this look just likes a regular animation where a box is enlarged until reaching a certain width. But let’s take a closer look at the step callback function.
It receives two parameters “now” and “fx.”
According the jQuery documentation, the two arguments represent the following:
The fx argument has a not-so-well-known property called “pos,” which works as kind of a “modulus.”
By using this modulus, we can control the animation and modify it at specific key frames in order to modify it on the fly.
In the example above, we change the color of the box at a specific time similar to a progress bar, and then we display the progress score by simply multiplying the fx.pos modulus by “100.”
See the demo in action below:
And here is the full link to Fiddle: http://jsfiddle.net/Yfx5Q/1/
Have fun playing with your animation.