jQuery Stop
The jQuery stop() method halts an animation or effect before it reaches its end. It is especially useful for sliding menus, tooltips, and any element the user might interact with rapidly, so animations do not pile up and play out one after another.
The stop() Method
The stop() method works on all jQuery effect functions, including sliding, fading, and custom animations. When you call it, the currently running animation on the matched elements stops immediately at whatever point it had reached.
Stopping a slide animation
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="stop">Stop</button>
<div id="panel" style="width:100px; height:100px; background-color:navy;"></div>
<script>
$("#stop").click(function(){
$("#panel").stop();
});
</script>
</body>
</html>The Two Optional Parameters
The full syntax is $(selector).stop(stopAll, goToEnd). Both parameters are booleans and both default to false. The first controls whether the whole animation queue is cleared; the second controls whether the current animation jumps straight to its finished state.
Clearing the Whole Queue
When you chain many animations together, they build up in the queue. Passing true as the first argument wipes out every queued animation at once, which is perfect for a 'stop everything now' button.
Stopping all queued animations
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="stopAll">Stop All</button>
<div id="box" style="width:100px; height:100px; background-color:tomato;"></div>
<script>
$("#stopAll").click(function(){
// clear the queue and freeze the current animation
$("#box").stop(true);
});
</script>
</body>
</html>Preventing Animation Build-Up
A classic problem with hover menus is that quickly moving the mouse in and out queues up many slide animations, so the menu keeps opening and closing long after you stop. Calling stop(true, true) at the start of each new animation cancels the leftover ones and lands cleanly on the newest effect.
A smooth hover menu
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="menu">Menu
<div id="submenu" style="display:none;">Submenu content</div>
</div>
<script>
$("#menu").hover(function(){
$("#submenu").stop(true, true).slideDown();
}, function(){
$("#submenu").stop(true, true).slideUp();
});
</script>
</body>
</html>- stop() with no arguments: stop the current animation, keep the queue.
- stop(true): clear the queue and freeze the current animation in place.
- stop(true, true): clear the queue and snap the current animation to its end.
- stop(false, true): finish the current animation immediately, then continue the queue.
Exercise: jQuery Stop
What does calling plain .stop() do to an element mid-animation?