stop()
MethodThe jQuery stop()
method halts the currently running jQuery animations or effects on the selected elements before they complete.
The basic syntax of the jQuery stop()
method is:
The parameters in the above syntax are explained as follows:
true
) or not (false
). The default is false
, allowing other animations in the queue to continue after stopping the current one.true
). The default is false
.Here's a simple example that demonstrates the jQuery stop()
method in action. You can start and stop the animation by clicking the button.
<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 applies to all jQuery effects, including fading, sliding, animated show and hide effects, and custom animations.
Here's another example of using this method: if you click the "Slide Toggle" button again while the animation is in progress but before it completes, the animation will reverse immediately from the current position.
<script>
$(document).ready(function(){
// Kill and toggle the current sliding animation
$(".toggle-btn").on("click", function(){
$(".box").stop().slideToggle(1000);
});
});
</script>
When creating animated hover effects, a common issue arises with multiple queued animations if you rapidly place and remove the mouse cursor. This happens because mouseenter
or mouseleave
events trigger quickly before the animation completes. To mitigate this issue and achieve a smooth hover effect, you can incorporate stop(true, true)
into the method chain, like so:
<script>
$(document).ready(function(){
$(".box").hover(function(){
$(this).find("img").stop(true, true).fadeOut();
}, function(){
$(this).find("img").stop(true, true).fadeIn();
});
});
</script>
Note: Using stop(true, true)
with jQuery clears all queued animations and jumps the current animation to its final value immediately.