简体   繁体   中英

jQuery + Stop + Callback Functions

From what I understand using .stop() will prevent the callback functions to fire, right?

Unfortunately, it seems that this does not work in my current script:

newSubMenu.stop().slideToggle(250, function() {
  newSubMenu.css('visibility', 'visible').addClass('open');
});

The animation now stops when double clicking, but newSubMenu still gets the class open and I cant figure out why.

The goal I am trying to achieve, is to NOT apply the class open until the animation is complete.

From the documentation :

When .stop() is called on an element, the currently-running animation (if any) is immediately stopped. … Callback functions are not called.

Callback functions are called if the third argument to stop() is true .

In the code you provide, though, the callback will run because you're stopping already running animations, not the slideToggle() animation which has yet to run when stop() is called.

Here is a working example showing the callback being stopped .

To see why this happens, you have to understand, what toggle does. Everytime you click, the slideToggle gets itself the information to slideDown or slideUp .

The conclusion is: everytime the toggle is complete, your function will be called and your newSubMenu gets the visibility:visible style , plus the class "open" if it doesn't exist.

Click-> Stop all animations on element -> toggle slide -> call/excecute function

.stop() can be used to stop currently running animations. Once the animation has been completed the callback will be executed. In order to stop the current animation and avoid the callback being called you need to do something like this;

newSubMenu.mouseover(function(){
    newSubMenu.slideToggle(250, function(){
        $(this).css('visibility', 'visible').addClass('open');
    });
}).dblclick(function(){

    // this will stop the execution of the .slideToggle animation
    // whitch will prevent the callback from being executed
    newSubMenu.stop();

});

jsFiddle example

jQuery has added an "always" callback in version 1.8:

always

Type: Function( Promise animation, Boolean jumpedToEnd )

A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8)

URL: http://api.jquery.com/animate/

This will be fired always, if an animation is regularly done or if you interupt it with stop() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM