Stop() in Jquery
In jQuery, the .stop() method is used to stop the currently running animations or effects on an element. This method is helpful when you want to prevent an animation from completing or to stop multiple queued animations at once.
The .stop() method can be particularly useful when working with animations or effects that might be interrupted or overridden by other events or actions, like mouse hover, clicks, or other triggers.
? Syntax
$(selector).<div "#box").animate({ width: "300px" }, 2000); // Animate to 300px width $("#box").hover(function() { $(this).stop(); // Stop the animation when hovering });</script>
In this example, the animation of the #box will be stopped if the user hovers over the element during the animation.
? 2. Stop Multiple Animations
If you have queued animations and you want to stop all of them:
"#box").animate({ width: "300px" }, 2000); // Animation 1 $("#box").animate({ height: "300px" }, 2000); // Animation 2 // Stop all queued animations after 1 second setTimeout(function() { $("#box").stop(true, true); // Stop all animations and clear the queue }, 1000);</script>
Here, the animations for both width and height will be stopped after 1 second, and the queue will be cleared.
? 3. Stop Animation and Go to the End
If you want the animation to complete immediately when you stop it:
"#box").animate({ width: "300px" }, 2000); // Start animation // After 1 second, stop the animation and jump to the end state setTimeout(function() { $("#box").stop(true, true); // Jump to the final width immediately }, 1000);</script>
In this example, the #box will go from 100px to 300px width. After 1 second, the animation will be stopped and immediately completed, setting the width to 300px.
? Summary of .stop() in jQuery
| Option | Description |
|---|---|
.stop() | Stops the current animation, leaving it at the current state. |
.stop(true, true) | Stops all queued animations and completes the current animation. |
.stop(true, false) | Stops the current animation but keeps the queued animations. |