Ortund Ortund - 4 years ago 112
jQuery Question

Displaying array contents on page with a loop in jquery

I have several strings I want to display in a div, but they should fade in/out and be replaced with the next string in the array looping back to the first.

Cork from #jquery on freenode IRC suggested I use .queue but it doesn't seem to be working. Nothing appears.

Where have I gone wrong here?

This code was based on the last example on jquery's .queue page

<div class="introText"></div>

<script>
/*
Fade each above string in and out as content for the div sequentially
in a loop
*/
var Messages = [
"Matured Dieting via Smartphone",
"The Academic IQHE Diet",
"For only R 400.00 / year",
"Follow this super diet on mobile",
"<a href=\"http://www.m.smartpeeps.co.za\">m.smartpeeps.co.za</a>"
];

function IntroText() {
var i = 0;
var Div = $(".introText");

// div text should start with Messages[0] and loop to
// Messages[4], the restart at Messages[0]
$.each(Messages, function() {
// hide the previously shown item
if (i == 0) {
if (i >= 4) {
$.queue(Div[0], "fx", function() {
$(this).hide("slow");
$.dequeue(this);
});
} else {
$.queue(Div[0], "fx", function() {
$(this).html(Messages[i - 1]).hide("slow");
$.dequeue(this);
});
}

// display the new item
$.queue(Div[0], "fx", function() {
$(this).html(Messages[i]).show("slow");
i = i++;
$.dequeue(this);
});
} else {
// loop back and display the first item again
$.queue(Div[0], "fx", function() {
i = 0;
$(this).html(Messages[i]).show("slow");
$.dequeue(this);
});
}
});
}

// run it
IntroText();
</script>

Answer Source

One solution is use a setInterval() for make a proper loop. Show and hide content with fadein() / fadeOut()and with modulo % you can check when the count must be restart. startMessage allow you to start loop message since any of item.

/*
        Fade each above string in and out as content for the div sequentially
        in a loop
    */
    var Messages = [
        "Matured Dieting via Smartphone",
        "The Academic IQHE Diet",
        "For only R 400.00 / year",
        "Follow this super diet on mobile",
        "<a href=\"http://www.m.smartpeeps.co.za\">m.smartpeeps.co.za</a>"
    ];
    

   
    function IntroText() {
        var Div = $(".introText")
        var startMessage = 0;
        setInterval(function(){
          Div.html(Messages[startMessage]).fadeIn().delay(1000).fadeOut();
          startMessage++;
          if(startMessage % Messages.length == 0){
            startMessage=0;
          }
        },2000)
    }

    // run it
    IntroText();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="introText" style="display:none"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download