Kevmon
Kevmon

Reputation: 1005

Wait for All Fades in a Function to Finish Before the Next Function Starts

I've looked and seen some responses to this type of problem, but still can't wrap my mind around it. I have a function with 5 different animations finishing at different times. I want this function to completely finish it's inner functions' animations before the next function starts.

HTML

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<div id="div5"></div>
<div id="div6"></div>

CSS

#div1 {
  background-color:red;
  width:100px;
  height:100px;
}
#div2 {
  background-color:blue;
  width:100px;
  height:100px;
}
#div3 {
  background-color:green;
  width:100px;
  height:100px;
}
#div4 {
  background-color:yellow;
  width:100px;
  height:100px;
}
#div5 {
  background-color:orange;
  width:100px;
  height:100px;
}
#div6 {
  background-color:black;
  width:100px;
  height:100px;
  display:none;
}

JQuery / JS

fadeAll(); // I want to wait for all of the fadeOuts in this function to complete before...
$('#div6').fadeIn(); // .. this function starts.

function fadeAll() {
  $('#div1').fadeOut('slow');
  $('#div2').fadeOut('fast');
  $('#div3').fadeOut();
  $('#div4').fadeOut('fast');
  $('#div5').fadeOut();  
}

Upvotes: 2

Views: 105

Answers (1)

Lajos Arpad
Lajos Arpad

Reputation: 76444

Take a look at jQuery's documentation about fadeout. There you will see that it can have a complete property. Let's see whether this example helps you:

var fades = 0;

function fadeOut(context, duration, callback) {
    fades++;
    context.fadeOut(duration, function() {
        fades--;
        if (typeof callback === "function") {
            callback();
        }
    });
}

function fadeAll(callback) {
  fadeOut($("#div1"), 'slow', callback);
  fadeOut($("#div2"), 'fast', callback);
  fadeOut($("#div3"), undefined, callback);
  fadeOut($("#div4"), 'fast', callback);
  fadeOut($("#div5"), undefined, callback);  
}

function fadeCallback() {
    if (fades === 0) {
        $('#div6').fadeIn();
    }
}

fadeAll(fadeCallback);

Here we have a counter to know how many fadeouts are we waiting for. We increase this number when a fadeOut is called and decrease it when such an event is completed. We decrease it before calling the callback and the callback checks that value. If it is 0, then callback is called.

Upvotes: 1

Related Questions