jQuery Stop Animations
In this tutorial you will learn how to stop running animations using jQuery.
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:
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
Try this code »<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
Try this code »<script>
$(document).ready(function(){
// Kill and toggle the current sliding animation
$(".toggle-btn").on("click", function(){
$(".box").stop().slideToggle(1000);
});
});
</script>
Creating Smooth Hover Effect
While creating the animated hover effect one of the common problem you may face is multiple queued animations, when you place and remove the mouse cursor rapidly. Because, in this situation mouseenter
or mouseleave
events are triggered quickly before the animation complete. To avoid this problem and create a nice and smooth hover effect you can add the stop(true, true)
to the method chain, like this:
Example
Try this code »<script>
$(document).ready(function(){
$(".box").hover(function(){
$(this).find("img").stop(true, true).fadeOut();
}, function(){
$(this).find("img").stop(true, true).fadeIn();
});
});
</script>
Note: The jQuery method stop(true, true)
clears all the queued animations and jumps the current animation to the final value.