HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

jQuery Stop Animations

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>
                  
              

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
<script>                  
$(document).ready(function(){
    $(".box").hover(function(){
        $(this).find("img").stop(true, true).fadeOut();
    }, function(){
        $(this).find("img").stop(true, true).fadeIn();
    });
});
<script>