jQuery has an
animate() method which affords us the ability to transition between CSS states over a given amount of time. Below are two divs, both of which have click events applied which will execute code that will change their width. The first box will use the
css() method to immediately change the property, while the second will use the
animate() method to specify the property to be changed as well as the duration of time over which it should occur.
$("#box1").click(function(){
$(this).css("width", "100%");
});
$("#box2").click(function(){
$(this).animate({"width": "100%"}, 2000);
});
You might notice that we're using a new syntax structure to provide the CSS property and the value we want to set it to. This is using an object map, which takes in pairs of property names and values. This can be used to modify multiple properties simultaneously.
$("#box3").click(function(){
$(this).animate({"width": "100%", "height": "300px", "lineHeight": "300px"}, 2000);
});
We can chain
animate() methods together as well as incorporate other jQuery timing methods such as
delay().
$("#box4").click(function(){
$(this).animate({"width": "100%", "height": "300px", "lineHeight": "300px"}, 2000)
.delay(2000)
.animate({"width": "100px", "height": "100px", "lineHeight": "100px", 2000});
});
If we want to animate a color change, we need to add the jQuery UI library, which augments the
animate() method.
$("#box5").click(function(){
$(this).animate({"width": "100%", "height": "300px", "lineHeight": "300px", "backgroundColor": "green"}, 2000)
.delay(2000)
.animate({"width": "100px", "height": "100px", "lineHeight": "100px", "backgroundColor": "white"}, 2000);
});
If we want to have an event occur at the end of the animation, we can provide a callback function which will be executed when
animate() is finished.
function boxOpen(){
$("#box6").html("I'm big and green!");
}
function boxClosed(){
$("#box6").html("click me");
}
$("#box6").click(function(){
$(this).animate({"width": "100%", "height": "300px", "lineHeight": "300px", "backgroundColor": "green"}, 2000, boxOpen)
.delay(2000)
.animate({"width": "100px", "height": "100px", "lineHeight": "100px", "backgroundColor": "white"}, 2000, boxClosed);
});