lundi 1 février 2016

random quote without back to back

I'm trying to pull a random quote from an array. I need to display an initial quote and then get a new one, no same two quotes back to back. Here's what I got.

$(document).ready(function() {

    var quoter = [{
    quote: "I drink to make other people more interesting.",
    author: "Ernest Hemingway"
}, {
    quote: "Alcohol may be man's worst enemy, but the bible says love your enemy.",
    author: "Frank Sinatra"
}, {
    quote: "Reality is an illusion created by a lack of alcohol.",
    author: "N.F. Simpson"
},{
    quote: "Time is never wasted when you’re wasted all the time.",
    author: "Catherine Zandonella"
},{
    quote: "I feel bad for people who don’t drink. When they wake up in the morning, that’s as good as they’re going to feel all day.",
    author: "Frank Sinatra"    
}];

    var randomQuote = Math.floor(Math.random() * quoter.length);
//$(function () {
    //Set Original Quote
    $('#quoteText').text(quoter[randomQuote].quote);
    $('#authorText').text(quoter[randomQuote].author);      
//});       

  $('#btnNew').click(function(evt) {
    //prevent browser's default action
    evt.preventDefault();
    //getting a new random number to attach to a quote and setting a limit
    var sourceLength = quoter.length;
    var randomNumber = Math.floor(Math.random() * sourceLength);


    //set a new quote
    //while ( randomNumber <= sourceLength ) {
        while (randomNumber === randomNumber){
      var newQuoteText = quoter[randomNumber].quote;
      var newQuoteGenius = quoter[randomNumber].author;

      var timeAnimation = 500;
      var quoteContainer = $('#quoteContainer');
      //fade out animation with callback
      quoteContainer.fadeOut(timeAnimation, function() {

        //set text values
        $('#quoteText').text(newQuoteText);
        $('#authorText').text(newQuoteGenius);

        //console.log(quoteText,authorText);

        //fadein animation.
        quoteContainer.fadeIn(timeAnimation);
      });

      break;

    }; //end while loop

  }); //end btnNew function

}); //end document ready

I need to do this by using a while loop. I can't figure out how to store the random quote (array value) and then compare it to the new random one to get a different random on if it's the same.

The HTML is here:

<div id="quoteContainer">
   <p><span id="quoteText"></span><Br/></p>
   &mdash;<span id="authorText"> </span>
</div>




Aucun commentaire:

Enregistrer un commentaire