JQuery Stop
The stop() method
The jQuery stop()
method is used to halt any current jQuery animations or effects on the selected elements until they finish.
The following is the basic syntax for the jQuery stop()
method:
$(selector).stop(stopAll, goToEnd);
The following are the definitions of the parameters in the above syntax:
-
The parameter stopAll Boolean determines if the queued animation should be deleted or not. The default value is wrong, meaning that only the animation currently playing is stopped; the rest of the queue animations are kept playable.
-
The goToEnd Boolean parameter determines whether the current animation should be completed immediately. False is the default value.
Here's a quick example that shows the jQuery stop() method in motion, with the animation starting and stopping on the click of a button:
$(document).ready(function(){
// Start animation
$(".start-btn").click(function(){
$(".obj").animate({left: "+=150px"}, 2000);
});
// Stop running animation
$(".stop-btn").click(function(){
$(".obj").stop();
});
// Start animation in the opposite direction
$(".back-btn").click(function(){
$(".obj").animate({left: "-=150px"}, 2000);
});
// Reset to default
$(".reset-btn").click(function(){
$(".obj").animate({left: "0"}, "fast");
});
});
Live Demo!
Here's another example of this method: after starting the animation but before it's done, if you press the "Slide Toggle" button again, the animation will start in the opposite direction from the saved starting point.
$(document).ready(function(){
// Kill and toggle the current sliding animation
$(".toggle-btn").on("click", function(){
$(".obj").stop().slideToggle(1000);
});
});
Live Demo!
Smooth hover effect
When you position and remove the mouse cursor quickly when creating an animated hover effect, one of the most common issues you can encounter is multiple queued animations. Since the mouseenter and mouseleave events are activated quickly before the animation is finished in this case. To avoid this issue and build a good, smooth hover effect, add the stop(true, true) method to the method chain, as shown below:
$(document).ready(function(){
$(".box").hover(function(){
$(this).find("img").stop(true, true).fadeOut(1000);
}, function(){
$(this).find("img").stop(true, true).fadeIn(1000);
});
});
Live Demo!