New quote on page refresh

时间:2016-07-11 19:05:30

标签: javascript jquery

I'm making a quote machine and the new quote button works, but how do I make it so a new quote is already loaded once you load/refresh the page? Right now you have to click on the "+" button to get one.

Fiddle: https://jsfiddle.net/hanyb9da/18/

Code for quote change:

$('#random-quote').click(function() {
    var randomIndex = Math.floor(Math.random() * quotes.length);
    var selectedQuote = quotes[randomIndex];

    $('#main-quote').text(selectedQuote.quote);
    var selectedBG = selectedQuote.background;
    console.log(selectedBG);
    $("body").css("background-image", "url('" + selectedBG + "')");
  });

Thank you :)

1 个答案:

答案 0 :(得分:3)

To achieve this you could trigger a click event right after you set the event handler:

$('#random-quote').click(function() {
    // your code here...
}).trigger('click'); // or just .click()

Alternatively you could put the logic which generates and displays the quote in to its own function which you can call on both the click of the button and the load of the page, like this:

function getQuote() {
    var randomIndex = Math.floor(Math.random() * quotes.length);
    var selectedQuote = quotes[randomIndex];

    $('#main-quote').text(selectedQuote.quote);
    var selectedBG = selectedQuote.background;
    console.log(selectedBG);
    $("body").css("background-image", "url('" + selectedBG + "')");
}

$('#random-quote').click(getQuote); // on click
getQuote(); // on load

Updated fiddle