Reputation: 256
I am looking to fade out an element then fade in the next element in series.
Can someone comment as to why this code doesn't work? It fades out the first element then fades in the next 3 elements at the same time.
<p id="ptag1">
Display this first
</p>
<p id="ptag2" style="display:none;">
Display this second
</p>
<p id="ptag3" style="display:none;">
Display this third
</p>
<p id="ptag4" style="display:none;">
Display this fourth
</p>
<script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var numberoflines = 5;
var o;
$(document).ready(function () {
for (i=1; i < numberoflines; i++)
{
fadeoutelement(i);
o = i + 1
fadeinelement(o);
}
});
function fadeoutelement(i) {
setTimeout("$('#ptag" + i + "').fadeOut(500)", 700);
}
function fadeinelement(o) {
setTimeout("$('#ptag" + o + "').fadeIn(500)", 1200);
}
</script>
Upvotes: 0
Views: 987
Reputation: 1101
Consider that your document is ready at time T=0, and so your for
loop is called. As the execution time of the for
loop itself is negligible, we can assume T=0 to be fixed throughout the execution of the for
loop. Now it, in turn, schedules fadeoutelement()
to execute at T=0+700, and 3 instances of fadeinelement()
at T=0+1200. And therefore, the latter 3 function calls are essentially simultaneous.
What you want is something like the following (working code):
var numberoflines = 5;
$(document).ready(function () {
var time = 0;
for (i=1; i < numberoflines; i++){
setTimeout("$('#ptag" + i + "').fadeOut(500)", time+700);
setTimeout("$('#ptag" + (i+1) + "').fadeIn(500)", time+1200);
time += 1200;
}
});
Upvotes: 2
Reputation: 3650
If you want the second element to wait for the first element to fade out before it fades in, it sounds like you would benefit from using a queue with multiple elements. Check out the FxQueues jQuery plugin https://github.com/lucianopanaro/jQuery-FxQueues
Check out their example code for usage: https://github.com/lucianopanaro/jQuery-FxQueues/blob/master/example.html
$("#1").animate({marginTop: "100px"}, {duration: 100, queue: "global"});
$("#2").animate({marginTop: "100px"}, {duration: 100, queue: "global"});
$("#3").animate({marginTop: "100px"}, {duration: 100, queue: "global"});
Or with your case
$("ptag1").fadeOut({duration: 500, queue: "global"});
$("ptag2").fadeIn({duration: 500, queue: "global"});
$("ptag2").fadeOut({duration: 500, queue: "global"});
$("ptag3").fadeIn({duration: 500, queue: "global"});
Upvotes: 3