[Solved] How do I display a random quote when page loads? Random Quote Machine

I would like a random quote (from my quotes) to appear when the page first loads, not just when someone clicks on the “random quote” button. How can I do that?

See my code here: https://codepen.io/velvetstar/pen/NrpqdR

One way you can do this is to trigger a click even on the button in the document.ready.

Another approach would be to move the click callback into its own function and invoke that function when the document is ready and on button click

My function that retrieves the random quotes is: getQuote. I tried putting window.onload=getQuote; in different places in my javascript code. That didn’t work. I even tried moving $(document).ready to the end of my javascript code. That didn’t work either.

As vdineva mentioned you can trigger a click, take a look at this page.


Add the necessary code inside document.ready after your handler.

Okay. So when the page loads, we want it to “trigger” the quote button that brings up a random quote as if it had actually been physically clicked. I came up with this:

$(’#quoteButton’).on(“click”, function () {

I have tried inserting this at different places in my code, and nothing changes. What am I doing wrong?

It looks like you have created the getQuote function within your click event. You could create your function before the click event:

function getQuote(
//create function


getQuote(); // call the function for a quote when the page loads


$("#quoteButton").on(“click”, function(){
}); //Call the function when the button is clicked

This is the way I tackled this issue


Thanks! That worked!

glad I could help you :slight_smile: