Reputation: 6635
as the title states, I am trying to iterate over a collection of child elements, the trouble comes in when I try to fade them out one at a time, I am using $.each()
to try and achieve this, but it seems to be fading everything out at once, what I would like it to do is wait for the animation to finish and then go to the next child element and fade that out, here is my code,
jQuery:
var children = $("container").children();
children.each(function(){
$(this).fadeOut('slow');
})
HTML:
<div id="container">
<div style="background: #F00;"></div>
<div style="background: #00F;"></div>
<div style="background: #0F0;"></div>
</div>
also, would it be possible to trigger an animation before the current one has finished, but delaying it by a set interval?
Thanks in advance!
Upvotes: 3
Views: 12678
Reputation: 4323
Giv for your DIV's own ID's and than you can itterate over the ID's and fading one at a time out. For example:
var children = $("container").children().each(function() {
for(var k=0;k< $(this).attr('id').length;k++)
{
$(this).attr('id',$(this).attr('id'));
}
$(this).attr('id').fadeOut('slow'); });
Upvotes: 0
Reputation: 10825
Here's a slightly different approach:
Create an array of all the children elements, as opposed to your initial code which used a jQuery object.
var children = [];
$("#container").children().each(function() {
children.push(this);
});
Create a function that pops one element at a time out of the array and animate it, recursively calling itself as a callback function so it will execute only AFTER the previous animation is finished.
function fadeThemOut(children) {
if (children.length > 0) {
var currentChild = children.shift();
$(currentChild).fadeOut("slow", function() {
fadeThemOut(children);
});
}
}
See a working demo on jsFiddle.
Hope this helps !
Upvotes: 15
Reputation: 13614
I think you'll want to use something like $.queue
so you're not manually coming up with durations and timing all of your animation yourself. jQuery's $.queue
documentation linked to this question on Stack Overflow which should point you in the right direction.
Upvotes: 1
Reputation: 100381
Do you want to fade one by one after the previous finish fading?
el.fadeOut("slow", function() {
// Fade next (see example)
});
.fadeOut( [ duration ], [ callback ] )
- duration: A string or number determining how long the animation will run.
- callback: A function to call once the animation is complete.
Upvotes: 2
Reputation: 22770
Add an increasing delay
for each subsequent fade:
var children = $("container").children();
var delayInterval = 0;
children.each(function(){
if (delayInterval > 0) $(this).delay(delayInterval);
$(this).fadeOut('slow');
delayInterval += 300;
})
You will probably need to adjust the delay increment to fit to your needs.
Upvotes: 1