SukhyGills SukhyGills - 5 months ago 23
Javascript Question

HTML/CSS - How to set text (e.g. 'Quote of the Day') to change automatically on page load/reload?

I am quite new to HTML/CSS. I've got a fairly basic website going in which I have a funny quote under my title. My friend asked me if it changes every time the page loads and that gave me the idea to do something like that. I was wondering if there was any way to manage this in HTML/CSS. I do know some Javascript, so I can also do it on that if needed.

Do I need a list of quotes saved in a file? Can they be pulled from a website/online list? What is the most efficient way to do this?



You can use Math.random() to get your randomized index. Math.random() generates a value from 0 (inclusive) to 1 (exclusive).

The onload will be called each time the page is loaded.

<!DOCTYPE html>
<body onload="randomQuotes()">

    <h1>Hello World!</h1>

    <p id="quote"></p>

    var quotes = ['hi', 'bye', 'lol', 'hello', 'world']
    function randomQuotes() {
        var idx = Math.floor(Math.random() * quotes.length)
        document.getElementById('quote').innerHTML = quotes[idx]