Reputation: 10887
I have pairs of elements that need to start fading out / in at the same time. That is, both elements in a pair should only start to fade in when the fade-out is complete; and to fade out when fade-in is done.
I basically use $.when
on both elements in a pair for both fade-in and fade-out. Basically, to wait until the fading completes. Is this correct? Anything simpler than this solution?
Complete code: jsFiddle
$.when($('.next-' + id).fadeOut(500)).done(function () {
var n = ...
$.when($('.next-' + n).fadeIn(500)).done(function () {
...
});
});
Also, .fadeOut()
returns a jQuery object. How can we pass it into $.when
, which expects a Deferred object? Help?
Upvotes: 2
Views: 1132
Reputation: 17579
There is simplier way. Just use .delay(x)
See my answer to this question jQuery Add then remove width to consecutive elements in a loop and your updated fiddle http://jsfiddle.net/RruxA/1/
var MAX = 2;
var animateCard = function (id) {
setInterval(function () {
var n = (id % MAX) + 1
$('.next-' + id).fadeOut(500)
$('.next-' + n).delay(500).fadeIn(800)
id = n
}, MAX * 1300);
}
animateCard(1);
Upvotes: 1
Reputation: 18078
You can exploit a feature of jQuery by which an animated jQuery collection will return a "promise of completion" with .promise()
:
I think this is what you are trying to achieve :
$('.next-' + id).fadeOut(500).promise().then(function() {
var n = ...;
return $('.next-' + n).fadeIn(500).promise();
}).then(function() {
...
});
Note that by building a .then()
chain in this way, we avoid a "pyramid of doom".
Things get a bit trickier if you are using an custom animation queue, but for the standard fx
queue (as in this case), everything is made very simple for you.
Upvotes: 3