I need that when one animation finishes in jQuery, another one will start. And this must be done in sequence (without running at the same time).
I saw in a project where I work a code that does this, but I believe it has many callbacks.
var speed = 1000;
var cb = undefined;
$(function() {
$('.item:eq(0)').animate({
opacity: 1
}, speed, function() {
$('.item:eq(1)').animate({
opacity: 1
}, speed, function() {
$('.item:eq(2)').animate({
opacity: 1
}, speed, function() {
$('.item:eq(0)').animate({
opacity: 0
}, speed, function() {
$('.item:eq(1)').animate({
opacity: 0
}, speed, function() {
$('.item:eq(2)').animate({
opacity: 0
}, speed, function() {
$.isFunction(cb) && cb();
})
})
})
})
})
})
});
.item {
height: 30px;
background: red;
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><ul><liclass="item">item</li>
<li class="item">item</li>
<li class="item">item</li>
</ul>
In this case, if we had more than 3 items (suppose we had 20), I would not like to have 20 callbacks.
The questions are:
- How could this code improve?
- How can I make these sequential animations in jQuery (one waiting for another)?