jQuery Animate()

jQuery Animate() Method

The jQuery animate() method is used to create custom animations.

Syntax

$(selector).animate({params},speed,callback);

  1. params - params parameter defines the CSS properties to be animated.

  2. speed -It specifies the speed of the animate effect. Possible values:

    • milliseconds
    • slow
    • fast
  3. callback - A function to be executed after the animation completes.

The following example demonstrates a simple use of the animate() method; it moves a <div> element to the right, until it has reached a left property of 200px. To manipulate the position, remember to first set the CSS position property of the element to relative, fixed, or absolute.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script> 
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '200px'});
});
});
</script> 
</head>
<body>

<button>Click to Start Animation</button>

<div style="background:red;height:80px;width:100px;position:absolute;"></div>

</body>
</html>

Output

jquery slideToggle method

Now click on the Click to Start Animation. It will move in left position of 200px as following:

jquery slideToggle method

jQuery animate() method using multiple properties

You can use multiple properties to animate at the same time.

Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script> 
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '200px',
opacity: '0.7',
height: '200px',
width: '150px'
});
});
});
</script> 
</head>
<body>
<button>Click to Start Animation</button>
<div style="background:red;height:80px;width:100px;position:absolute;"></div>
</body>
</html>

Output

jquery Animate method

Now click on the Click to Start Animation. The following css proprties will apply to move left.

left: '200px',
opacity: '0.7',
height: '200px',
width: '150px'

Now animated box looks like that:

jquery Animate method
Prev Next