jQuery animate()

jQuery library supports the animate() method which can be used to create custom animations.

Syntax:

$(selector).animate({params},speed,callback);
  • Params is a required parameter that is used to set the desired CSS properties for the animation.
  • The optional parameters like speed and callback are the same as in other jQuery effect methods.

Important features of jQuery animate():

  • The jQuery animate() method can animate multiple properties at the same time.

Example1:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '100px',
opacity: '0.1',
height: '80px',
width: '80px'
});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>My ball is moving and fading away.</p>
<div style="background:red;height:100px;width:100px;position:absolute;border-radius:120px"></div>
</body>
</html>

 

This method can also define relative (to the element’s current value) values using += or -=.

Example2:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
height: '+=250px',
width: '+=250px'
});
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>My ball is moving and even its size is increasing.</p>
<div style="background:blue;height:10px;width:10px;position:absolute;border-radius:120px"></div>
</body>
</html>

Example3:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
height: 'toggle'
});
});
});
</script>
</head>
<body>
<p>Click me again and again. I love toggling</p>
<button>Start Animation</button><br>
<div style="background:yellow;height:100px;width:100px;position:absolute;border-radius:60px"></div>
</body>
</html>

 

In case of multiple animate() calls, jQuery runs the animate calls one by one in a queue.

Example4:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var div = $("div");
div.animate({height: '200px', opacity: '0.4'}, "slow");
div.animate({width: '200px', opacity: '0.8'}, "fast");
div.animate({height: '100px', opacity: '0.4'}, "slow");
div.animate({width: '100px', opacity: '0.8'}, "fast");
});
});
</script>
</head>
<body>
<button>Start Animation</button>
<p>Watch me!</p>
<div style="background:red;height:100px;width:100px;position:absolute;border-radius:120px"></div>
</body>
</html>