Custom Animations with animate()
In this page:
Basic animate()
The animate() method smoothly transitions one or more numeric CSS properties on an element to new target values over a set duration. It only works on properties with numeric values, like width or opacity, not on colors without a plugin.
Example: Basic animate()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:100px">Box</div>
<script>
$("#box").animate({width: "300px"});
</script>
</body>
</html>
Multiple Properties
Passing an object with several properties, like {width: 200px, opacity: 0.5}, animates all of them together in one call, saving you from chaining multiple separate .animate() calls that would otherwise run out of sync.
Example: Multiple Properties
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:100px;opacity:1">Box</div>
<script>
$("#box").animate({width: "200px", opacity: 0.5});
</script>
</body>
</html>
Duration
The second argument to animate() sets how long the transition takes, either as milliseconds or a keyword like slow or fast, giving you direct control over animation pacing.
Example: Duration
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="width:100px">Box</div>
<script>
$("#box").animate({width: "300px"}, 2000);
</script>
</body>
</html>
Opacity
Opacity is one of the few non-pixel numeric properties animate() understands out of the box, letting you fade an element in or out as part of a larger multi-property animation.
Example: Opacity
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box">Box</div>
<script>
$("#box").animate({opacity: 0});
</script>
</body>
</html>
Relative Values
Prefixing a target value with += or -=, like {left: '+=50px'}, animates a property relative to its current value instead of to an absolute one, which is useful for nudging an element by a fixed amount regardless of its starting position.
Example: Relative Values
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="box" style="position:relative;left:0px">Box</div>
<script>
$("#box").animate({left: "+=50px"});
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: