jQuery Animate and the Step Callback

Hey, this is turning into a jQuery blog! Believe it or not I really do other types of development too. It’s been a while though and this post is a quick share of something that has not seen a lot of coverage, hope it comes in handy.

So that library jQuery has that .animate() method, that has them options, with one being the step callback – looking like this.

$( 'span' ).animate({ 
	// Properties of the elements to animate
	opacity: 0.25,
	left: '+=50'
},
{
	// step is a callback for each step of the animation
	step: function( now, fx ) {
		// do stuff...
	}
});

Nothing new, nothing fancy, but if you look at the two arguments being applied, things start to get kinda interesting. Especially when the latter being the jQuery.fx prototype object, you suddenly have a load of properties to utilize – one of them being the fx.pos. This is a modulus 1 kinda value that sweeps from 0 to 1 through the duration of the animation, allowing you to animate other stuff that can be calculated using that factor.

There’s probably not a lot of use cases for the next example, but it shows the callback and arguments in use in a simple way – click result to see the animation.

Note that both this and fx.elem is a reference to the element currently being animated.

A more useful scenario is one where I had to do a quick poll type functionality for a project. After vote was given, I wanted the polling result to animate and count to the resulting score. All I had to do was to multiply it by fx.pos.

// Calculate score by multiplying by fx.pos that sweeps from 0.0 to 1.0.
step: function( now, fx ) {
	$span.text( Math.floor( fx.pos * score ) + '%' );
}

Here’ a simple version of how it turned out – submit your answer.

And here’s a link to the full fiddle.

Cheers.


One Response to jQuery Animate and the Step Callback

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>