jQuery: interrupting fadeIn()/fadeOut()

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 11:16:19

stop() will only remove animations that are not executed yet.

use stop(true, true) to interrupt and remove the current animation too!

You will get smooth fadeIn/Out effect by clearing queue but not jumping to the end, using .stop(true,false), but please notice that as FadeIn can be interrupted this way, FadeOut can not. I reported it as a bug like years ago, but noone cared. FadeIn only works if the object is hidden. But there is workaround... use FadeTo instead - it works on hidden as well as partially faded objects:

    $('.a').hover(function(){
    $('.b').stop(true,false).fadeTo(3000,1); // <- fadeTo(), not FadeIn() (!!!)
},function(){
    $('.b').stop(true,false).fadeOut(3000);
});

Here's how it works: http://jsfiddle.net/dJEmB/

AFAIK fadeIn and fadeOut run synchronously, so no, I do not think you can interrupt them while they are running. You would have to wait until it is done executing.

If you call the stop method on the element it will stop all animations. The reason the fadeOut call in your example isn't called until after fadeIn is because animations are executed in a queue-like fashion.

You can use the stop() function to interrupt any animation that takes place during that particular moment. Let me know if this works.

Its always a good practice to keep functions that deal with an animation etc inside the function's callback. You can tell if the fadeIn() has finished by doing your function from within its callback, like:

$element.fadeIn(200, function(){
   //do callback
});

If that is not possible then you can declare a variable outside the function. Say, var elmFadeInRunning = false. Change it to true right before you call fadeIn and change it back to false in the callback of the fadeIn. That way you can know if its still running if elmFadeInRunning == true.

Another working example

<div id="fadediv">Yay, I like to fade</div>
<button id="stopdatfade" >Stop that fade!</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
(function($){ 

    currentfade = $("#fadediv").fadeOut(5000).fadeIn(5000).fadeOut(5000).fadeIn(5000); 
    $('#stopdatfade').on('click', function () { 
        if (typeof currentfade !== 'undefined') { 

            currentfade.stop(true, true);

        } 

    }); 
})(jQuery);
</script>

Try taking animation out from queue.

$('...').fadeIn(200).dequeue().fadeOut(0);

http://api.jquery.com/queue/

http://api.jquery.com/dequeue/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!