Fun with jQuery.animate();

Fun with jQuery.animate();

With CSS3 transitions getting more popular, the jQuery.animate() is often the last choice in animating elements on web pages. I can understand why, it is somewhat choppier on most browsers, compared to the smoother hardware-accelerated CSS animations.

However, I found that you can actually use jQuery.animate() to do quite a number of things that doesn't relate to moving things around the browser window. Let's see one example:

  1. var countstart = {number: 0}, countend = {number: 1000};
  2.  
  3. jQuery(countstart).animate(countend, {
  4. duration: 800,
  5. step: function() {
  6. $("#counter").html( Math.round(this.number) );
  7. },
  8. });

See It In Action!

I've just used jQuery.animate to actually animate a number counting up.

The magic lies in the 'step' property of the optional values that you can pass to the .animate() function. The function defined in 'step' will be executed every single step of the animation. In the example above, we are passing an object with only one property - 'number'. So for 800 milliseconds (which is defined in the 'duration' property), 'number' will be incremented until it reaches 1000.

Note: I've added the Math.round() function in there because it tends to return me float numbers for some reason.

In other words, you can 'animate' any property of any object, it doesn't have to be a CSS property at all. The best part of this? It actually supports jQuery easing!

See It In Action - with Easing!

3 Comments

Leave a Reply