Jump to content

i need code to display random quote from a document or list.

Recommended Posts

  • Replies 1
  • Views 1.1k
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

I provided a solution for this earlier this year on the Circle Forum so I've duplicated this below for you.

It should be as simple as adding something like this to a Code Block. The button caption can be changed to meet your needs and you can edit the strings and add more. 

<button id="randomStringButton">Get Random String</button>
    <p id="randomString"></p>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const randomStringButton = document.getElementById("randomStringButton");
    const randomStringDisplay = document.getElementById("randomString");

    // JSON data with strings to display
    const jsonData = {
        "strings": [
            "String 1",
            "String 2",
            "String 3",
            "String 4",
            "String 5"
        ]
    };

    const strings = jsonData.strings;

    // Function to get a random string from the JSON list
    function getRandomString() {
        const randomIndex = Math.floor(Math.random() * strings.length);
        return strings[randomIndex];
    }

    // Display a random string when the button is clicked
    randomStringButton.addEventListener("click", function () {
        const randomStr = getRandomString();
        randomStringDisplay.textContent = randomStr;
    });
});
</script>

Did this help? Please give feedback by clicking an icon below  ⬇️

Me: I'm Paul, a SQSP user for >18 yrs & Circle Leader since 2017. I value honesty, transparency, diversity and good design ♥.
Work: Founder of SF.DIGITAL. We provide high quality original extensions to supercharge your Squarespace website. 
Content: Views and opinions are my own. Links in my posts may refer to my own SF.DIGITAL products or may be affiliate links.
Forum advice is completely free. You can thank me by selecting a feedback emoji. Buying a coffee is generous but optional.

Would you like your customers to be able to mark their favourite products in your Squarespace store?

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.