animate() Method : Animation in Jquery

Date Published: 27/04/2020 Published By: JaiSchool

animate() is a predefined function in the Jquery library. It is used to create animations by giving CSS properties and values in its first parameter.

  • A curly brace must surround properties & values {} .
  • Both should be in a separate double or single quote.
  • Separate property and value with a colon.
  • To write another property: value, terminate the first property with a comma.

The second parameter of the animate() method contains timing in milliseconds to execute property: value from the first argument/parameter. Or you can also use "slow" (600ms) and "fast" (200ms) as a string to define timing.

Jquery's animate() Method Syntax

animate({"property":"value"},speed,easing,callback);

Example-

<head>
<title>Jquery animate() function</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
	<h1>Welcome</h1>
<div style="border:5px solid red;"></div>
<script>
$(document).ready(function(){
  $("div").animate({
     "width":"500px",
     "height":"300px"
	},3000);
});
</script>
</body>

easing parameter of animate()

We define easing function in third argument of the animate() function. See example below.

<head>
	<title>Jquery</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
	<button id="btn">Animate</button>
<div style="border:5px solid red;width:400px;"></div>
<script>
$(document).ready(function(){
	$("#btn").click(function(){
	animation();
	function animation(){
  		$("div").animate({"height":"500px"},1500);
  		$("div").animate({"height":"300px"},1500);
  		$("div").animate({"width":"800px"},1500);
  		$("div").animate({"width":"400px"},1500,animation);
	}
	});
});
</script>
</body>

Another callback function can be defined in the last argument of animate() that will execute when the animation lasts.

<head>
	<title>Jquery</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<body>
	<button id="btn">Animate</button>
<div style="border:5px solid red;width:400px;"></div>
<script>
$(document).ready(function(){
	$("#btn").click(function(){
	animation();
	function animation(){
  		$("div").animate({"height":"500px"},1500,function(){alert("jaischool");});
	}
	});
});
</script>
</body>

Publish A Comment

Leave a Reply

Your email address will not be published.