0

I am trying to get a set of strings in an array to fade in and out, then change to the next string in the array. The code below skips directly to the third element in the array. I can't see how or why.

var msg = ["Test Number 1", "Test Numero Dos", "Test, the third"];

$( document ).ready(function(){
    fade();
    setInterval(fade, 15000);
});

function fade() {
  var i;
  for (i = 0; i < msg.length; ++i) {
    $('#message').html(msg[i]);
    $('#message').fadeIn(1000, function(){
      $('#message').delay(30000).fadeOut(1000); 
    });
  };

}
<div id="message" style="display:none;">TEST MESSAGE</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

1 Answer 1

2

Let the setInterval do the actual fading. Don't do any for/loops inside the actual function, or you defeat the purpose of the fade (It's looping through the entire array right then and there quickly, and displaying the last result). The fade function should simply get the next index of the array, and do the fading for that element:

var msg = ["Test Number 1", "Test Numero Dos", "Test, the third"];

$( document ).ready(function(){
    fade();
    setInterval(fade, 5000);
});

var i = 0;
function fade() {
  $('#message').fadeOut(1000, function() {
    $('#message').html(msg[i++ % msg.length]);
    $('#message').fadeIn(1000)
  });
}
<div id="message" style="display:none;">TEST MESSAGE</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

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

3 Comments

That did it. Thanks!
One quick question though, I'm having trouble figuring out how to set the duration that the message stays on screen. I tried to use a .delay again on the fadeout, but this just seems to increase the time between the messages appearing. What's the best way to handle that?
Just change the 5000 in setInterval(fade, 5000); @MichaelGajeski

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.