Saturday, July 9, 2011

jQuery Animations and Effects

You can slide elements, animate elements, and even stop animations in mid-sequence. To slide elements up or
down:

$("#myElement").slideDown("fast", function() {
// do something when slide down is finished
}

$("#myElement").slideUp("slow", function() {
// do something when slide up is finished
}

$("#myElement").slideToggle(1000, function() {
// do something when slide up/down is finished
}

To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles, but instead of setting them instantly (as CSS or raw JavaScript would do), it does so gradually, animating the effect at the chosen speed:

$("#myElement").animate(
{
opacity: .3,
width: "500px",
height: "700px"
}, 2000, function() {
// optional callback after animation completes
}
);

Animation with jQuery is very powerful, and it does have its quirks (for example, to animate colors, you need a special plugin). It's worth taking the time to learn to use the animate command in-depth, but it is quite easy to use even for beginners.

No comments:

Post a Comment