jQuery Animations
The jQuery animate() method is used to create custom animations.
Syntax: $(selector).animate({params},speed,callback);
The required params parameter defines the CSS properties to be animated.
The optional speed parameter specifies the duration of the effect. ("slow", "fast", or milliseconds.)
The optional callback parameter is a function to be executed after the animation completes.
Example 1: Move Div using Animate method.
$(document).ready(function () { $("button").click(function () { $("div").animate({ left: '250px' }); }); });
Example 2: Animate multiple css properties at the same time.
$(document).ready(function () { $("button").click(function () { $("div").animate({ left: '250px', opacity: '0.5', height: '150px', width: '150px' },500); }); });
Example 3: Animate using Relative value. This is done by putting += or -= in front of the value:
$(document).ready(function () { $("button").click(function () { $("div").animate({ left: '+=250px', height: '150px', width: '150px' }); }); });
Example 4: Animate using toggle Height:
Animate multiple css properties (Queue Functionality)
By default, jQuery comes with queue functionality for animations. This means that
if you write multiple animate() calls one after other, then jQuery creates an "internal"
in these method calls and runs the animate calls ONE by ONE.
So, if you want to perform different animations after each other, we can take the
advantage of the queue functionality.
Example 5: Animate multiple css properties (Queue Functionality)
Example 6: Animate multiple css properties (Queue Functionality)
jQuery Stop() Method
The jQuery stop() method is used to stop an animation or effect before it is finished.
Syntax: $(selector).stop(stopAll,goToEnd);
The optional stopAll parameter specifies whether also the animation queue should be cleared or not. Default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards.
The optional goToEnd parameter specifies whether or not to complete the current animation immediately. Default is false.
Example 7: jQuery Stop() Method.
jQuery Chaining Method
Till now we have been writing jQuery statements one at a time (one after the other).
However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s).
To chain an action, you simply append the action to the previous action.
The following example chains together the css(), slideUp(), and slideDown() methods. The "p1" element first changes to red, then it slides up, and then it slides down.
Example 8: jQuery Chaining Method.