Let me preface this by saying I am new to Javascript, but not to programming. I call fadeOut on a jQuery Object like such:
$(x).fadeOut('fast');
I have other things that will be fading out and in, but I need them to wait for each other, and I do not necessarily know how many are going to be doing this. x is a string from an array that contains the items that are are fading in or out. In my first attempt I used the callback function in fadeOut like this:
$(x).fadeOut('fast', function(){ foo(modifiedArray); })
Where foo is the method I want, and modifiedArray is the array minus x. This still didn’t make it wait though, so next I tried:
$(x).fadeOut('fast');
while( $(x).css('display') != 'none' ){}
foo(modifiedArray);
But the loop never ends. How can I make the animation wait before I call foo(modifiedArray) again?
EDIT: Here is the full code
function animateElements(elements){
if (elements.length == 1){
var x = elements[0];
$(x).fadeIn('slow');
}
else{
var x = elements.pop();
$(x).fadeOut('fast');
while( $(x).css('display') != 'none' ){}
animateElements(elements);
}
}
For the sake of completeness. In your code you can fix the following things.
Use
.fadeIn()instead of.fadeOut().You may want to use
.shift()instead of.pop()to go over the array from left to right, not from right to left.Call the recursive step in the complete callback of
.fadeOut()avoiding to check compulsively the element’s style.Use
elements.length == 0as a base case. This will improve readability.At the end, the code will look like this:
See it live.