Pankaspe Pankaspe - 1 month ago 8
Javascript Question

stop the loop in javascript

I'm new to javascript. I have found this script http://jsfiddle.net/jfriend00/n4mKw/ for text slideshow, I love it!

(function() {

var quotes = $(".quotes");
var quoteIndex = -1;

function showNextQuote() {
++quoteIndex;
quotes.eq(quoteIndex % quotes.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextQuote);
}

showNextQuote();

})();


But how can I set loop to false?
I have 5 quotes, and after the slide I want to show the last quote fixed

Answer

Please give a look to the updated JSFiddle:

  var quotes = $(".quotes");
  var quoteIndex = -1;

  function showNextQuote() {
    ++quoteIndex;

    var $el = quotes.eq(quoteIndex % quotes.length)
      .fadeIn(2000)
      .delay(2000);

    if ((quoteIndex % quotes.length) < (quotes.length - 1)) {
      $el.fadeOut(2000, showNextQuote);
    }
  }

  showNextQuote();

What you have to do is to split the statement:

    quotes.eq(quoteIndex % quotes.length)
        .fadeIn(2000)
        .delay(2000)
        .fadeOut(2000, showNextQuote);

in two parts. The first part which control the fade in of the element:

var $el = quotes.eq(quoteIndex % quotes.length)
      .fadeIn(2000)
      .delay(2000);

The second part which checks to fade out or not that element:

if ((quoteIndex % quotes.length) < (quotes.length - 1)) {
  $el.fadeOut(2000, showNextQuote);
}