jQuery animate examples

Filed Under: jQuery

jQuery animate() function is used to perform a custom animation of a set of CSS properties. This method allows you to create custom animation only on numeric properties. For example, the properties with numeric values such as width, left, height, opacity can be used with animate() method, but the property like background-color cannot be animated since it has a string value.

jQuery animate

Here are the general syntaxes used by the animate() method:

  • animate({properties}, speed, easing, callback)
  • animate(properties, options)

{properties} defines the property : value pair of the CSS style class.

speed defines the duration of the effect. “slow”, ”fast” and the numeric values in milliseconds are generally used.

easing defines which easing function like “swing” or “linear” is used for animation.

callback specifies which function to be called after the animation is completed.

options define the additional options for the animation like speed, easing, callback, step, queue, specialEasing etc.

jQuery animate example

We will create animation like below using jQuery animate function.

jQuery animate examples

Following code demonstrates how to achieve above animation, we will also use animate() method with a call back. The runAnimation() method contains the code to animate. The callBackAnimation() method is called on completion of the animation and used to create the alert.


<!DOCTYPE html>
<html>
<head>
<title> JQuery Animation</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    var div = $("div");
    runAnimation();
    function runAnimation(){
      div.animate({height:300},"slow");
      div.animate({width:300},"slow");
      div.css("background-color","green");  
      div.animate({height:100},"slow");
      div.animate({width:100},"slow",callBackAnimation);
    }
function callBackAnimation(){
      alert("Animation completed");
    }

  });
});
</script>
</head>
<body>
  
<button>Run</button>
<div style="width:70px;height:70px;position:absolute;left:20px;top:50px;background-color:red;"></div>

</body>
</html>

Click on below link to see the demo page and try yourself.

jQuery animate Demo

jQuery performs custom animation with the animate() method. This method cannot be employed to animate the non-numeric properties. The animate method uses CSS style class properties with numeric values for animation.

For a real life example, please check out jQuery scroll to top.

Reference: API Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages