jQuery stop() Method
The jQuery stop() method is used to stop the jQuery animations or effects currently running on the selected elements before it completes.
The basic syntax of the jQuery stop() method can be given with:
$(selector).stop(stopAll, goToEnd);
The parameters in the above syntax have the following meanings:
- The optional stopAll Boolean parameter specifies whether to remove queued animation or not. Default value is
false, that means only the current animation will be stopped, rest of the animations in the queue will run afterwards. - The optional goToEnd Boolean parameter specifies whether to complete the current animation immediately. Default value is
false.
Here’s a simple example that demonstrates the jQuery stop() method in real action in which you can start and stop the animation on click of the button.
Example
<script>
$(document).ready(function(){
// Start animation
$(".start-btn").click(function(){
$("img").animate({left: "+=150px"}, 2000);
});
// Stop running animation
$(".stop-btn").click(function(){
$("img").stop();
});
// Start animation in the opposite direction
$(".back-btn").click(function(){
$("img").animate({left: "-=150px"}, 2000);
});
// Reset to default
$(".reset-btn").click(function(){
$("img").animate({left: "0"}, "fast");
});
});
</script>
Note: The jQuery stop() method works for all jQuery effects such as fading, sliding, animated show and hide effects as well as custom animations.
Here’s one more example of this method in which, if you click the “Slide Toggle” button again after starting the animation but before it is completed, the animation will begin in the opposite direction immediately from the saved starting point.
Example
<script>
$(document).ready(function(){
// Kill and toggle the current sliding animation
$(".toggle-btn").on("click", function(){
$(".box").stop().slideToggle(1000);
});
});
</script>