Animating Function
Some of the standard effects that jQuery offers are powerful. Animation of page elements once had to be done by tricky hand-coded routines using JavaScript timers. Those capabilities are neatly wrapped into a few jQuery methods that you can call for your elements or collections of elements.
Fading
You can fade an element in or out, optionally setting the transition duration and adding a callback function.
To fade out to invisibility:
$("#elem").fadeOut("slow", function() { // do something after fadeOut has finished executing });
Or to fade in:
$("#elem").fadeIn(500, function() { // do something after fadeIn has finished executing });
You can also fade an element only partially, either in or out:
$("#elem").fadeTo(3000, 0.5, function() { // do something after fade has finished executing });
The second parameter (here set to 0.5) represents the target opacity. Its value works similarly to the way opacity values are set in CSS. Whatever the value of opacity before the method is called, the element will be animated until it reaches the value specified in the argument.
Sliding
You can slide elements, or collections of elements, upward or downward. The jQuery methods for sliding an element are direct corollaries to the fading methods you’ve just seen, and their arguments follow exactly the same rules:
$("#elem").slideDown(150, function() { // do something when slideDown is finished executing });
And to slide up:
$("#elem").slideUp("slow", function() { // do something when slideUp is finished executing });
In case you need to slide an element up or down depending on its current state, jQuery also provides a handy slideToggle() method:
$("#elem").slideToggle(1000, function() { // do something when slide up/down is finished executing });
Animation
To animate an element, you do so by using jQuery to specify the CSS styles that the item should have applied. jQuery will impose the new styles, but can do so gradually (instead of applying them instantly as in plain CSS/JavaScript), thus creating an animation effect.
You can use animate() on a wide range of numerical CSS properties. In this example the width and height of an element are animated to a size of 400 x 500 pixels; once the animation is complete, the callback function is used to fade the element to invisibility:
$("#elem").animate( { width: "400px", height: "500px" }, 1500, function() { $(this).fadeOut("slow"); } );