jQuery: stopping animations

jQuery animations are grouped together into queues. These queues are handled internally by the fx object. Sometimes, however, we need more control over the queuing process. Consider the case of a simple fade effect using the hover() event. Without controlling the underlying queue, you often get undesired results. For that reason, jQuery provides the stop() method to stop and reset a queue with its animations. Its syntax is as follows:

element.stop(clearQueue, jumpToEnd)

This method accepts two Boolean parameters which by default are set to false. The first parameter clears the animation queue so that the current animation stops. The second parameter, instead, forces the current animation to be completed before stopping it. Coming back to the use case mentioned earlier, we can set both parameters to true to fix the aforementioned problem with hover():

$(function() {

  $('li', '#navigation').each(function() {
  
    var $li = $(this);
    var $a = $li.find('a');
    
    $a.hover(function() {
    
      $a.next().stop(true, true).fadeIn(1000);
    
    }, function() {
    
      $a.next().stop(true, true).fadeOut(1000);
    
    
    });
  
  });

});

Now our effects will work as expected, without any trailing side effect. You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.