This page covers various uses of the jQuery animate method, which allows users to create custom animations.
Syntax:
$(selector).animate({params}, speed, callback)
The {params} parameter specifies the CSS properties that will be animated.
The optional speed parameter specifies the speed at which the animation occurs.
The optional callback parameter specifies a function that will run as soon as the effect has completed.
Let's start with a simple animation example, then we'll look into more intricate uses of jQuery animate().
Example:
The following jQuery code will move the square HTML div to the right, increase the size of the text in the div, and change the opaqueness of the div's background color.
Hello World!
A few things to note from this example...
You may have noticed the use of += for changing the width property. In the example, this code means "increase the div's width by 300px. This is why the div get wider each time you click on the button.
In the CSS for the div, the position was set to relative. In CSS all elements default to a static position, so we set the position to relative (or sometimes absolute) to allow the div to move to the right when the left property is changed.
You can change multiple CSS properties in one animate() call!
If you continue to click the button, the div stops moving to the right? This happens because the div reached left: 250px. How might you change the jQuery code so that it continues to move to the right?
The font size was changed with the variable fontSize. Remember that in JavaScript, variables are camel-cased, so even though the CSS property is font-size, with jQuery, it must be camel-cased to fontSize.
Now, what if we want to animate something multiple times in a row, each time with different animations?
If you write multiple calls to animate(), each call will be executed one after another.
In this code screenshot, jQuery creates a queue of the successive calls to animate() and processes them one after another.
Try this example problem:
Problem:
Animate the HTML div such that when the button is clicked, the div will slowly move in a digital figure 8 motion (shown below) and the opacity of the background color will change.