How to Randomly Cycle through Text on Button Click

Happy Valentine’s Day everyone! :love_letter:

Need a last minute gift idea? :wink: I loved eating those Sweethearts candies as a kid, so I recreated the experience on Wix Studio! 🩷

This also demonstrates how to randomly cycle through text. Here’s how you can add this kind of feature to any of your sites:

:one: Create an array of all your text options as Strings
:two: Create a function to generate a random number
:three: In an onClick event handler for the button (or event handler of your choice), generate a random number from 0 to the length of the text options array
:four: Use that random number as an index to pull from your text options array

Here’s the code I used:

const textOptions = [
    'BE MINE',
    'LOVE YOU',
    'TEXT ME',
    'CUTIE PIE',
    'XOXO',
];

//Returns random integer from 0 to max-1 (excluding max)
function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}

$w.onReady(function () {
    $w('#randomizeBtn').onClick(() => {
        let randomIndex = getRandomInt(textOptions.length);
        $w('#heartText').text = textOptions[randomIndex];
    });
});

Hope this helped! :revolving_hearts:

2 Likes