Search code examples
jqueryanimationcallbackjquery-callback

prevent callbacks from being stopped when stopping parent function in jquery?


It goes a little something like this:

$("example").hover(function(){
        ("example").stop().show(/*More Code*/, callback());
    }, function(){
        ("example").stop().hide(/*More Code*/, callback());
    }
)

So if the mouse were to leave the area before the first animation completed it would stop all animations, and skipping over the callbacks. Is there a way to use stop() and still execute the callback functions?


Solution

  • Use a setTimeout that is timed to fire at the end of the animation instead of a callback.

    $("example").hover(function(){
            $("example").stop().show(1000);
            setTimeout(function() { /* do something */ }, 1000);
        }, function(){
            $("example").stop().hide(1000);
            setTimeout(function() { /* do something */ }, 1000);
        }
    );
    

    Another option would be to use .stop(true,true) instead of just .stop().

    This clears the queue, sends the animation to the end, and fires the callback.

    $("example").hover(function(){
            $("example").stop(true,true).show(1000);
        }, function(){
            $("example").stop(true,true).hide(1000);
        }
    );