Search code examples
javascriptloopsquotes

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();

})();
.quotes {display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<h2 class="quotes">first quote</h2>
<h2 class="quotes">second quote</h2>
<h2 class="quotes">third quote</h2>

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


Solution

  • 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);
    }