TranceFusion TranceFusion - 11 days ago 7
Javascript Question

jQuery show/hide each element in list

The problem is that I want to change innerHTML propery of for each name in list and animate it with (fadeIn,delay for x sec,fadeOut)

<div id="welcomeBox">Welcome SOMETHING</div>

var list = ["George","Bob","Tom"];

$.each(list, function()
{
$("#welcomeBox")
.eq(0)
.text('Welcome' + this)
.fadeToggle(1500)
.delay(5000)
.fadeToggle(1500);
});


With code above I just get 3x Welcome Tom message.

Answer
var list=["George","Bob","Tom"];

// recursive closure to iterate thru list
(function recurse(index){
    // on fade use the callback to fade out
    $("#welcomeBox").text('Welcome ' + list[index]).fadeIn(1500, function(){
        $("#welcomeBox").fadeOut(1500, function(){
            // after fade out, call the function again with the next index
            recurse(undefined !== list[index+1] ? index+1 : 0);
        });
    });
})(0);

https://jsfiddle.net/6qo0L6mr/