Reputation: 57176
Any idea how to animate the opacity of each certain element one by one up to 16 targets/ elements only?
This will change the opacity of the elements all together,
$('.block-item').animate({
opacity:0
},500);
Have a look here.
But I want the opacity to change one after another. and this will stop when it reaches the 16th element.
Here is the html,
<div id="parent_container">
<div class="block-item">1</div>
<div class="block-item">2</div>
<div class="block-item">3</div>
<div class="block-item">4</div>
<div class="block-item">5</div>
<div class="block-item">6</div>
<div class="block-item">7</div>
<div class="block-item">8</div>
<div class="block-item">9</div>
<div class="block-item">10</div>
<div class="block-item">11</div>
<div class="block-item">12</div>
<div class="block-item">13</div>
<div class="block-item">14</div>
<div class="block-item">15</div>
<div class="block-item">16</div>
<div class="block-item">17</div>
<div class="block-item">18</div>
</div>
I came out this function but it crashes any browser on it,
function opacity_test(index)
{
$('.block-item').eq( index ).animate({
opacity:0
},500);
setInterval( function() {
opacity_test(index + 1);
}, 1000 );
}
Thanks.
Upvotes: 8
Views: 12004
Reputation: 339816
You can use the "completion callback" of .animate()
to start the next fade:
function fade(index) {
$('.block-item').eq(index).animate({
opacity: 0
}, function() {
// on completion, recursively call myself
// against the next element
if (index < 15) {
fade(index + 1);
}
})
}
fade(0);
See http://jsfiddle.net/alnitak/3DuTG/
Upvotes: 9
Reputation: 146310
Try this:
var delay = 0;
$('.block-item:lt(16)').each(function(){
//^^ do for every instance less than the 16th (starting at 0)
$(this).delay(delay).animate({
opacity:0
},500);
delay += 500;
});
Fiddle: http://jsfiddle.net/maniator/VS8tQ/3/
Upvotes: 22
Reputation: 40863
An option using the callback, and to stop when it reaches the 16th element you can use .index()
var f = function($current) {
$current.animate({
opacity: 0
}, function() {
if ($current.next(".block-item").index() < 15) {
f($current.next(".block-item"));
}
});
};
f($(".block-item:first"));
Upvotes: 4