Fun with jQuery’s “animate()”

jQuery’s animation capabilities are normally either overlooked or overused. Some people consider animation on the web to be a fruitless endeavor while others seem to never get enough of it. Yet most don’t realise what jQuery allows you to do; it’s no longer just about accordions and slideshows!

The animate method is incredibly versatile; it doesn’t have to manipulate a CSS property; any property of any object can be manipulated. This allows us to do things like this:

var from = {property: 0};
var to = {property: 100};
 
jQuery(from).animate(to, {
    duration: 100,
    step: function() {
        console.log( 'Currently @ ' + this.property );
    }
});

The step function you see is an optional property of the also-optional object argument (the second one we’re passing to animate()). If the step function exists jQuery will run it on every single step of any animaton. This gives you limitless control, allowing you to manipulate any number of things.

The News Ticker

I know it’s an old and boring effect but I can’t resist; jQuery makes it so damn easy!

var text = 'jQuery is simply awesome! Blah blah blah!';
var span = $('<span/>').appendTo('body');
 
jQuery({count:0}).animate({count:text.length}, {
    duration: 1000,
    step: function() {
        span.text( text.substring(0, Math.round(this.count)) );
    }
});

SEE IT IN ACTION!

Did you notice the easing!?

Easing

Another commonly overlooked feature of jQuery animation is easing. There are two places you can specify what easing to utilise; either as the third argument or as a property to the alternative two-argument call (see the docs):

var duration = 1000;
var easing = 'linear';
var callback = function(){};
 
/* #1 */
jQuery('something').animate({prop:1}, duration, easing, callback);
 
/* #2 */
jQuery('something').animate({prop:1},{
    easing: easing,
    duration: duration,
    complete: callback
});

Only two easing “equations” are bundled with jQuery, “linear” and “swing”. By default jQuery uses “swing”. There are many additional “equations” available. You just need to include jquery.easing.js and you can use them in all your animations!

When I originally stumbled upon the easing plugin I really only wanted one thing; I clear way to illustrate what each easing-method did! I recently setup a page to do just that! Check it out!

Ok, this post wasn’t very long (the easing demo took longer than I anticipated); the gist of it is: There are still many undiscovered secrets within jQuery… “animate()” being one of them.