Eddy Eddy - 6 months ago 17
Javascript Question

changing text after period, in an endless cycle

I have text that I want to change after a certain period of time. I have this working:

function nextMsg() {
if (messages.length == 0) {

} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};

var messages = [
"sleep",
"eat",
"drink",
"read",
].reverse();

$('#message').hide();
nextMsg();


See the JSFIDDLE

My question:
I want to keep repeating the messages. In other words, when the last message is displayed, to start the cycle again from the first message creating an endless cycle. What needs to be changed / added to the code?

Answer

I hope this will work for you.

var fadeLoop = function($el) {
    $el.fadeOut(1000, function() {
        var $next = $el.next();
        if ($next.length == 0) {
            $next = $el.siblings(":first");
        }
        $next.fadeIn(1000, function() {
            fadeLoop($next);
        });
    });
};

$(document).ready(function(){
    $("#elm1").siblings().hide();
    fadeLoop($("#elm1"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Things to do:
<div >
<span id="elm1">sleep</span>
<span id="elm2">eat</span>
<span id="elm3">drink</span>
<span id="elm4">read</span>
  </div>

Source : http://jsfiddle.net/KWmgf/

Comments