Saturday, 2 June 2012

Stop and complete all jQuery animations immediately

Problem:

I'd like to stop and complete all jQuery animations immediately. At one point my web app needs to progress to another stage and the smooth completion of several pending, long animations isn't needed.

Solution:

Edit: have a look at the comment below by Navigator regarding .finish() (see jQuery doc for the .finish() function). It's valid for jQuery 1.9 and above =) The points written in this post were tested for the jQuery version that was used when this post was originally written June 2012.

There are several ways to immediately stop and complete all animations that are currently running or pending in jQuery. Two of those methods will be outlined here.

One way to do this is by setting the jQuery.fx.off parameter to true, e.g.

jQuery.fx.off = true;

This will cause all queued animations to skip immediately to the final frame and complete. Note that while this parameter is set to true all animations will skip to their final states. To allow jQuery animations later on, set this parameter back to false.

The second way is more of a shotgun approach and probably isn't a good way to skip over animations in the general case. However, if you haven't been keeping track of all the selected elements that have a pending animation and thereby can't use the stop() method on them individually, you can try selecting all elements and calling the stop() function, e.g.

$("*").stop(true, true);

Note that the latter is extremely inefficient since it selects all elements on the page!

Notes:

These methods were tested on jQuery version 1.7.2 on Firefox 12.0 and the iOS 5.1 browser.

It isn't quite clear whether the jQuery.fx.off method will skip currently running animations to the final frame.

References:

2 comments:

  1. From my understanding and tests, jQuery.fx.off will only skip animations to the end that are defined after the flag is set to true. Any animations already running will simply continue.

    The manual of jQuery states this explicitly - although the text can be easily mistaken:

    When this property is set to true, all animation methods will immediately set elements to their final state when called...

    Mind the "when called" in this sentence. There is nothing said about finishing cued animations.

    stop() is also not the best alternative. The call that really does what you describe would be $("*").finish();

    Here is a fiddle that shows the effects of fx.off and of finish():
    http://jsfiddle.net/au6qS/1/
    Click the red bar to start three animations - after the second fx.off is set.
    Click the green bar to issue a finish().

    ReplyDelete
  2. Thanks for the clarification @Navigator! The jsfiddle demo illustrated your point quite well.

    ReplyDelete