2

I found this answer:

How can I change text after time using jQuery?

Which basically does what I need. But instead of having it redirect to another page at the end, I want it to just keep cycling through the text messages infinitely. Obviously, I remove the IF section to stop the redirecting, but how do I make it repeatedly cycle through the text messages?

function nextMsg() {
    if (messages.length == 0) {
        // once there is no more message, do whatever you want
        alert("redirecting");
    } else {
        // change content of message, fade in, wait, fade out and
        // continue with next message
        $('#message').html(messages.pop()).fadeIn(500).delay(1000)
                                          .fadeOut(500, nextMsg);
    }
};

// list of messages to display var messages = [
//   "Hello!",
//   "This is a website!",
//   "You are now going to be redirected.",
//   "Are you ready?",
//   "You're now being redirected..."
// ].reverse();

// initially hide the message $('#message').hide();

// start animation nextMsg();
1
  • 3
    You can encase you code inside setInterval() and run it using a timespan Commented Sep 24, 2012 at 20:23

2 Answers 2

5

Just make small changes in the basic code:

function nextMsg(i) {
    if (messages.length == i) {
        i = 0;
    }

    $('#message').html(messages[i])
                 .fadeIn(500)
                 .delay(1000)
                 .fadeOut(500, function() {
                     nextMsg(i + 1);
                 });
};

nextMsg(0);​

DEMO: http://jsfiddle.net/8wqv2/

Sign up to request clarification or add additional context in comments.

3 Comments

I updated your fiddle so that now it's shorter: jsfiddle.net/8wqv2/1 I dropped the whole if statement and called nextMsg(++i%messages.length) instead.
Ah, I see what you're doing there! That makes sense. Thank you!
Thanks all! That's perfect, and even more important, I follow the logic. I'm learning!
0

Would something like this work?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.