Waxi
Waxi

Reputation: 1651

Don't understand why my setInterval + jQuery doesn't work

To summarize, I'm trying to have a random quote generator. My code is pretty simple...

var myQuotes = [

    {
    quote: "To err is human; to forgive, divine.",
    cite: "Alexander Pope"},

    {
    quote: "Reports of my death have been greatly exaggerated.",
    cite: "Mark Twain"} 

];

var randomQuote = Math.floor(Math.random() * myQuotes.length);

$('.quote').html(myQuotes[randomQuote].quote); // #1
$('.cite').html(myQuotes[randomQuote].cite); 

setInterval(function() {

    $('.quote').fadeOut();

    $('.quote').fadeIn().html(myQuotes[randomQuote].quote); // #2

}, 3000);

On load, it displays #1 just fine, but #2 doesn't seem to work...it just keeps flashing the same one from before, the one in #1. What am I not understanding about this?

Upvotes: -1

Views: 217

Answers (1)

Amar Syla
Amar Syla

Reputation: 3643

You'll have to put the randomQuote variable inside the setInterval, so it updates:

setInterval(function() {

    randomQuote = Math.floor(Math.random() * myQuotes.length);

    $('.quote, .cite').fadeOut("slow", function() {
        $('.quote').fadeIn("slow").html(myQuotes[randomQuote].quote);
        $('.cite').fadeIn("slow").html(myQuotes[randomQuote].cite);
    });

}, 3000);

http://jsfiddle.net/av1xg897/1/

Upvotes: 5

Related Questions