In this tutorial, you'll gain a deeper understanding of jQuery's capabilities by learning to create custom animation effects. We'll focus on using the animate()
method to create your own animations from scratch.
What You'll Learn:
animate()
method.Prerequisites:
Before starting this tutorial, you should have:
The animate()
method in jQuery allows you to create custom animation effects on HTML elements. It works by gradually changing CSS styles over a set duration.
Syntax: $(selector).animate({styles},duration,easing,callback);
Let's create a simple animation that changes the height and width of a div.
Example 1:
HTML:
<div id="myDiv">Hello, World!</div>
<button id="startBtn">Start Animation</button>
CSS:
#myDiv {
width: 100px;
height: 100px;
background-color: red;
}
JavaScript:
$("#startBtn").click(function(){
$("#myDiv").animate({
width: "200px",
height: "200px"
}, 2000);
});
When you click on the "Start Animation" button, the div will gradually increase its width and height to 200px over a duration of 2000 milliseconds (2 seconds).
Example 2:
Let's add easing and a callback function to our animation.
JavaScript:
$("#startBtn").click(function(){
$("#myDiv").animate({
width: "200px",
height: "200px"
}, 2000, "linear", function(){
alert("Animation Complete!");
});
});
Now, the animation speed is constant, and an alert box pops up after the animation.
We've learned how to create custom animations in jQuery using the animate()
method. We've also seen how to control the speed, easing, and completion of these animations.
Next Steps:
fadeIn()
, fadeOut()
, slideUp()
, slideDown()
, toggle()
.Additional Resources:
Exercise 1: Create a div that changes its color over a duration of 5 seconds.
Exercise 2: Create a div that moves diagonally across the screen.
Exercise 3: Create a div that grows in size, changes color, then shrinks back to its original size. Use a callback function to alert when the animation is complete.
Solutions and Explanations:
Color change is not directly supported by animate()
, but jQuery UI extends this functionality. Check out the Color Animation documentation.
You can animate the top
and left
css properties to make the div move diagonally.
Chain multiple animate()
calls to create a sequence of animations. The callback function in the last animate()
will execute after all animations are complete.
Happy animating!