jQuery Animation Effects
jQuery animate() Method
The jQuery animate() method is used to create custom animations. The animate() method is typically used to animate numeric CSS properties, for example, width, height, margin, padding, opacity, top, left, etc. but the non-numeric properties such as color or background-color cannot be animated using the basic jQuery functionality.
The basic syntax of the jQuery animate() method can be given with:
$(selector).animate({ properties }, duration, callback);
The parameters of the animate() method have the following meanings:
- The required properties parameter defines the CSS properties to be animated.
- The optional duration parameter specifies how long the animation will run. Durations can be specified either using one of the predefined string 'slow' or 'fast', or in a number of milliseconds; higher values indicate slower animations.
- The optional callback parameter is a function to call once the animation is complete.
Here's a simple example of the jQuery animate() method that animates an image from its original position to the right by 300 pixels on click of the butto
Example
<script> $(document).ready(function(){ $("button").click(function(){ $("img").animate({ left: 300 }); }); }); </script>
Animate Multiple Properties At Once
You can also animate multiple properties of an element together at the same time using the animate() method. All the properties animated simultaneously without any delay.
Example
<script> $(document).ready(function(){ $("button").click(function(){ $(".box").animate({ width: "300px", height: "300px", marginLeft: "150px", borderWidth: "10px", opacity: 0.5 }); }); }); <script>
Animate Properties with Pre-defined Values
In addition to the numeric values, each property can take the strings 'show', 'hide', and 'toggle'. It will be very helpful in a situation when you simply want to animate the property from its current value to the initial value and vice versa.
Example
<script> $(document).ready(function(){ $("button").click(function(){ $(".box").animate({ width: 'toggle' }); }); }); <script>