Effects / Animations

Some of the features of the "Web 2.0" era websites is their ability to animate themselves. This is a good tool for adding an extra level of pizazz to a website, and if done well (and in moderation) can add a more professional look to your pages.

jQuery provides some methods for accomplishing basic animations.

How to fade content in or out

jQuery has the .hide() and .show() methods for hiding and showing content respectively. These essentially set the CSS display property to none/block. But this doesn't help when you want something to fade in.

The good news is that these methods take an argument to indicate how long the hide/show process should take.

$("#mydiv1").hide("slow");
$("#mydiv2").hide(3000);
$("#mydiv3").show("fast");
$("#mydiv4").show("2000");

The argument we use can be one of the known strings ("slow", "normal", "fast"), or it can be a numeric value indicating the number of milliseconds. If a speed is specified, then all matched elements will have their opacity changed over the specified period of time to either hide or show the element(s) as required.

How to slide a page element into place or out of site

Sliding content down into place is a nice feature that can make an interface entertaining and engaging. But more importantly it can be used to reduce clutter when there is a lot of content to be shown. So it is also important to hide content when it's not in use. But the hiding of the content should complement the showing routine. jQuery provides three simple animation routines for this purpose - the .slideDown(), .slideUp(), and .slideToggle() methods.

The three methods all take the same arguments - a speed, and a callback. Both of these are optional.

  • Speed - a string value of "slow", "normal", or "fast", or an integer value representing how many milliseconds the slide effect should take.
  • Callback - a function to be executed when the slide effect is completed. Allowing for chaining of effects or refreshing elements once content has been hidden/shown.

In all three cases, you get a reference to the element(s), and then call the methods:

$("div.effects").slideDown();
$("div.effects").slideDown("slow");
$("div.effects").slideDown(5000);
$("div.effects").slideDown(500, function () { alert("Done!"); });
//
$("div.effects").slideUp();
$("div.effects").slideUp("slow");
$("div.effects").slideUp(5000);
$("div.effects").slideUp(500, function () { alert("Done!"); });
//
$("div.effects").slideToggle();
$("div.effects").slideToggle("slow");
$("div.effects").slideToggle(5000);
$("div.effects").slideToggle(500, function () { alert("Done!"); });

The .slideToggle() method is a shortcut. It will check to see if the element is visible - if it is, the .slideUp() method is initiated. If it is not visibile, the .slideDown() method is initiated.