Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fadeOut callback executes before animation is complete

Tags:

jquery

I was under the impression that the css rules in the callback function below would not execute until after the fadeOut was complete. That doesn't seem to be the case. The lines in the callback function are actually executing on click. Any ideas where I'm going wrong?

$('a.close_link, #lightbox').click(function(){  
    $('#lightbox, .lightbox_panel').fadeOut(300,function(){
        $('.instructor_video').css('left','150%');
        $('.instructor_bio').css('left','50%');
    });
    return false;
 });
like image 284
SideDishStudio Avatar asked Mar 25 '11 01:03

SideDishStudio


2 Answers

It's likely that your '#lightbox, .lightbox_panel' selector is matching an already hidden element. Keeping in mind that the .fadeOut() and the callback is called for each element that selector matches, you have to also realize that for already hidden elements the complete callback is called immediately (the work it has to done is....completed, right?).

To eliminate the "instant finish" here, you can just hide the :visible elements that actually need hiding, like this:

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

Or you can get at the same elements a bit differently with a .filter() call, like this:

$('#lightbox, .lightbox_panel').filter(':visible')
like image 177
Nick Craver Avatar answered Oct 27 '22 19:10

Nick Craver


the complete callback passed to fadeOut is executed once for each element that is animated, when that element is done animating. So if your #lightbox, .lightbox_panel selector matches more than one element, your callback will get called more than once.

If you want to wait until all are complete, 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%');
});
like image 38
Brandon Avatar answered Oct 27 '22 21:10

Brandon