Animation Queues and stop()
In this page:
Queue Animations
By default jQuery adds each new animation on an element onto a queue, so they play one after another instead of overlapping. This keeps multi-step effects looking smooth instead of jumping between conflicting states.
Example: Queue Animations
<!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;height:100px">Box</div>
<script>
$("#box").animate({width: "200px"}).animate({height: "200px"});
</script>
</body>
</html>
Queue on Repeated Clicks
If a user clicks a button that triggers an animation multiple times in quick succession, each click adds another animation to that element's queue, which can make the UI feel sluggish or unresponsive if left unchecked.
Example: Queue on Repeated Clicks
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="btn">Animate</button>
<div id="box" style="width:100px">Box</div>
<script>
$("#btn").on("click", function() {
$("#box").animate({width: "+=20px"});
});
</script>
</body>
</html>
stop()
Calling stop() halts whichever animation is currently running on an element, but leaves any animations still waiting in the queue to begin playing next.
Example: stop()
<!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>
<button id="stopBtn">Stop</button>
<script>
$("#box").animate({width: "500px"}, 3000).animate({height: "300px"}, 3000);
$("#stopBtn").on("click", function() {
$("#box").stop();
});
</script>
</body>
</html>
stop(true)
Calling stop(true) both halts the current animation and clears out the rest of the queue, preventing any queued-up animations from running at all.
Example: stop(true)
<!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>
<button id="stopBtn">Stop</button>
<script>
$("#box").animate({width: "500px"}, 3000).animate({height: "300px"}, 3000);
$("#stopBtn").on("click", function() {
$("#box").stop(true);
});
</script>
</body>
</html>
stop(true,true)
Calling stop(true, true) clears the queue and also jumps the current animation straight to its final values, which is the pattern most commonly used to make hover effects feel instantly responsive.
Example: stop(true,true)
<!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>
<button id="stopBtn">Stop</button>
<script>
$("#box").animate({width: "500px"}, 3000);
$("#stopBtn").on("click", function() {
$("#box").stop(true, true);
});
</script>
</body>
</html>
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: