开发者

jQuery .animate chains, callbacks, and .stop(true, true)

开发者 https://www.devze.com 2022-12-27 13:11 出处:网络
So I have a animation chain (.animate().animate().animate()), and on the last .animate(), there is a callback to do some clean-up.

So I have a animation chain (.animate().animate().animate()), and on the last .animate(), there is a callback to do some clean-up.

The animation is triggered by the hash in the address changing (#page1, #page2, etc.开发者_Go百科) -- so when the user changes the history state rapidly, if there is a currently executing animation, it needs to stop so they don't queue up. The problem is, if I add a .stop(true, true), it appears only to jump to end of the currently running animation -- and executes only its callback, if there is one. What I need is for it to jump to the end of all of the chained animations, and fire all of the callbacks (well, really just the last one).

Is this possible somehow? Huge thanks.


The answer is very simple. Thanks to JacobM for inspiration.

(function($){
    $.fn.extend({
        hardStop: function(){
            return this.each(function(){
                var e = $(this);
                while (e.queue().length){
                    e.stop(false, true);
                }
            });
        }
    });
})(jQuery);

$("#element").hardStop();

Late edit: I noticed that on complicated animation chains it's necessary to make sure that completing a callback doesn't add more functions to the fx queue of an already "cleared" element (given that multiple elements are included in the original selector):

(function($){
    $.fn.extend({
        hardStop: function(){
            var stopped = false
            while (!stopped) {
                this.each(function(){
                    var e = $(this);
                    while (e.queue().length){
                        e.stop(false, true);
                    }
                });
                stopped = true;
                this.each(function(){
                    var e = $(this);
                    if (e.queue().length){
                        stopped = false;
                    }
                });
            }
        }
    });
})(jQuery);

I have a feeling this solution could be made simpler...

0

精彩评论

暂无评论...
验证码 换一张
取 消