To animate an element in jQuery, animate() method is used to perform a custom animation of a set of CSS properties. It is an inbuilt method used to change the state of an element with CSS style. Using this, you can change the element from one state to another with the style properties such as width, height, and opacity.

Syntax for animate() method

Let’s see the basic syntax of the animate() jQuery method, which is given below:

(selector).animate({styles},speed,easing,callback)

Styles defines one or more CSS properties value to animate and a required property.

Speed is an optional one, which is used to specify the speed of the animation effect.

Easing is also optional and used for animation function like swing or linear.

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

Simple Example for animate()

Following program is a simple example to show how the animate () function is used.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("#box").animate({height: "300px"});
  });
  $("#btn2").click(function(){
    $("#box").animate({height: "100px"});
  });
});
</script>
</head>
<body>
<button id="btn1">Animate height</button>
<button id="btn2">Reset height</button>
<div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;"></div>
</body>
</html>

Leave a Reply

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