FadeOut callback is executed before the animation finishes

I had the impression that the css rules in the callback function below would not be executed until fadeOut was complete. This does not seem to be the case. Lines in the callback function are actually executed when clicked. Any ideas I'm wrong about?

$('a.close_link, #lightbox').click(function(){ $('#lightbox, .lightbox_panel').fadeOut(300,function(){ $('.instructor_video').css('left','150%'); $('.instructor_bio').css('left','50%'); }); return false; }); 
+4
source share
2 answers

Your selector '#lightbox, .lightbox_panel' matches an element that is already hidden. Bearing in mind that .fadeOut() and a callback are called for each element that the selector selects, you should also understand that for already hidden elements, complete callback is called immediately (the work that it should do is completed, right?).

To eliminate the "instant completion" here, you can simply hide the elements :visible that really need to be hidden, for example:

 $('#lightbox:visible, .lightbox_panel:visible').fadeOut(300,function(){ $('.instructor_video').css('left','150%'); $('.instructor_bio').css('left','50%'); }); 

Or you can get the same elements differently by calling .filter() , for example:

 $('#lightbox, .lightbox_panel').filter(':visible') 
+13
source

the full callback passed to fadeOut is performed once for each animated element when that element is executed by animation. Therefore, if your #lightbox, .lightbox_panel matches multiple elements, your callback will be called more than once.

If you want to wait until everything is done, you can do something like:

 var items = $('#lightbox, .lightbox_panel'); var count = items.length; items.fadeOut(300, function() { if (--count > 0) return; $('.instructor_video').css('left','150%'); $('.instructor_bio').css('left','50%'); }); 
+2
source

Source: https://habr.com/ru/post/1345177/


All Articles