I'm trying to create a callback function which loops my word animation. I created a jquery function which fades in and out each word with a certain color. I would like this small animation to loop correctly. The issue is that once I callback the function it does not start from the beginning, it repeats again the last code. So this in this example, you will see the key word mult-purpose two times.
Click here to see a temporal sample of what I mean.
This is my jquery code:
function wordfade(){
$('#msg').fadeIn(2000, function() {
$('#msg').html("Sustainable").css("color", "#3AE44E").delay(800).fadeOut(2000, function() {
$('#msg').fadeIn(2000).html("Eye Catching").css("color", "#F18D0B").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Modern Design").css("color", "#0B8DF1").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Energy Efficient").css("color", "#AD0BF1").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Restaurant").css("color", "#F10B0B").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Retail & Pop-Up").css("color", "#C39813").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Event Space").css("color", "#4FB186").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Bar & Lounge").css("color", "#F10BA3").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Residential").css("color", "#C7C7C7").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Hotel & Lodging").css("color", "#565457").delay(800).fadeOut(2000, function(){
$('#msg').fadeIn(2000).html("Multi-Purpose").css("color", "#F1880B").delay(800).fadeOut(2000, wordfade);
})
})
})
})
})
})
})
})
})
})
});
}
wordfade();
The first line of your function does a .fadeIn()
and waits until that's finished before setting the .html()
on the next line. So the second time it fades in while the html content is still the final word. Just combine the first two lines to look more like the other lines and it will work:
function wordfade() {
$('#msg').fadeIn(2000).html("Sustainable").css("color", "#3AE44E").delay(800).fadeOut(2000, function () {
$('#msg').fadeIn(2000).html("Eye Catching").css("color", "#F18D0B").delay(800).fadeOut(2000, function () {
// etc.
Demo: http://jsfiddle.net/PNDg4/
And then consider rewriting the whole thing to avoid so many nested callbacks:
var words = [
{ word : "Sustainable", color : "#3AE44E" },
{ word : "Eye Catching", color : "#F18D0B" },
{ word : "Modern Design", color : "#0B8DF1" },
{ word : "Energy Efficient", color : "#AD0BF1" },
/* etc */],
current = -1;
function wordfade() {
current = (current + 1) % words.length;
$("#msg").html(words[current].word)
.css("color", words[current].color)
.fadeIn(2000)
.delay(800)
.fadeOut(2000, wordfade);
}
wordfade();