Quick Tip: Add Easing to Your Animations

Easing can really bring life to an effect. Easing controls how an animation progresses over time by manipulating its acceleration. jQuery has two built-in easing methods: linear and swing. While they get the job done, they are pretty boring when compared to what's made available through the jQuery easing plugin.

The jQuery easing plugin offers 30 different easing methods, courtesy of Robert Penner's easing equations. Let's check some of them out.

Easing can only be applied when using the .animate() method. The effects helper methods like .show('fast'), .toggle('fast'), fadeIn('fast'), and so on all just use the default easing, "swing."

There are two ways to use easing with the .animate() method. For example, let's say we want to animate the opacity of a particular div. The first way to call .animate() is like this:

[js]$('#myDiv').animate( { opacity: 0 }, // what we are animating 'fast', // how fast we are animating 'swing', // the type of easing function() { // the callback alert('done'); }); [/js]

The second way is very similar and might even look the same at first glance.

[js]$('#myDiv').animate( { opacity: 0 }, // what we are animating { duration: 'fast', // how fast we are animating easing: 'swing', // the type of easing complete: function() { // the callback alert('done'); } }); [/js]

The difference is that the second method signature takes only two arguments: the properties we are animating and an object literal of settings/options. The first method signature separates out the settings/options into individual arguments.

jQuery Easing Plugin

Finally, let's look at a few of the 30 easing methods provided by the easing plugin.

Ease Out Bounce

[js]$(document).ready(function() { $('#easing_example_1').click(function(event) { $(this) .animate( { left: 200 }, { duration: 'slow', easing: 'easeOutBounce' }) .animate( { left: 0 }, { duration: 'slow', easing: 'easeOutBounce' }); }); });[/js]
Click Me

 

Ease Out Elastic

[js]$(document).ready(function() { $('#easing_example_2').click(function(event) { $(this) .animate( { left: 200 }, { duration: 'slow', easing: 'easeOutElastic' }) .animate( { left: 0 }, { duration: 'slow', easing: 'easeOutElastic' }); }); });[/js]
Click Me

 

Ease Out Back

[js]$(document).ready(function() { $('#easing_example_3').click(function(event) { $(this) .animate( { left: 200 }, { duration: 'slow', easing: 'easeOutBack' }) .animate( { left: 0 }, { duration: 'slow', easing: 'easeOutBack' }); }); });[/js]
Click Me

 

jQuery UI Easing

jQuery UI includes the easing plugin as part of its Effects Core. It also extends the effects helper methods to support the use of easing and even other types of effects. You can find the documentation for jQuery UI Effects here.