Arun O Arun O - 1 month ago 6
HTML Question

Fade out and replace a div multiple times

Okay. So I have a div and I figured out how to fade it out and replace it with certain text.

However, I want the second text that fades in to also fade out and a third div to fade in. After that, I want the fourth div to replace the third and so on.

How exactly can I go about achieving this?

Here's my code: http://jsfiddle.net/9Dubr/1/

<div id="foo">test</div>

$('#foo').delay(5000).fadeOut("slow", function(){
var div = $("<div id='foo'>test2</div>").hide();
$(this).replaceWith(div);
$('#foo').fadeIn(500);
});

Answer

Try this recursive function

function fadeMessages(arr) {
    if (arr.length == 0) return;
    $('#foo').fadeOut("slow", function(){
        $("#foo").html(arr[0]).hide().fadeIn("slow", function() {
            arr.shift();
            fadeMessages(arr);
        });
    });
}

fadeMessages(["good", "morning", "to", "everyone", "<img src='https://38.media.tumblr.com/avatar_4892c96bf7cb_128.png'><br><button> OK </button>"]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="foo">test</div>