Easing in jQuery 1.4a2

I’m happy to write that my proposed change has been accepted into the jQuery “fx” core. I thought it worth explaining how this feature works and how you can make it work in your code.

Currently, jQuery (1.3) only allows you to specify one easing function per animation. This is perfectly fine in most situations but in some unique cases there is a need for a different easing function for each animated CSS property. I mentioned, in my previous post on the topic, that such a thing could be emulated by initiating two separate animations and disabling the default animation queueing on the first one. It does work, but it’s a bit of a hack, and I felt that the API could be easily extended to serve these types of use cases.

So, as of jQuery 1.4 alpha version 2, jQuery provides you with the possibility of defining an easing function (or rather, the name of an easing function) for each property that you’re animating. It’s done in the following manner:

jQuery(myElement).animate({
    left: [500, 'swing'],
    top: [200, 'easeOutBounce']
});

Another possibility is to define the per-property easing functions within the optional options object, passed as the second argument to animate:

jQuery(myElement).animate({
    left: 500,
    top: 200
}, {
    specialEasing: {
        left: 'swing',
        top: 'easeOutBounce'
    }
});

See a demo!

The conventional easing argument can still be used to set a default easing function for those properties that don’t already specify a “special” easing function:

jQuery(myElement).animate({
    x: [100, 'easeInQuad'],
    y: [100, 'easeOutBounce'],
    z: 100
}, 1000, 'linear');

The z property will be animated using the linear easing function, and the other two properties (x and y) will be animated using their respective easing functions.

Any array specified as a value within the “properties” object (the first argument to animate) is assumed to be specifying both a value and an easing function just for that property. You can continue to use animate in the traditional way; no incompatibilities have arisen!

The easing function you specify is the only easing function that will be used for that property. Unlike the demos shown in my previous post on the topic, the functions are not overlaid — it’s either one or the other.

Note that you must download the easing functions in order to use them in your animations — they’re not included in the jQuery core (other than the default “swing”, and “linear”).

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!