Hi. I’m creating a site on Wix. However, I have run into a barrier with one of my features. The databases can’t pick a random value for my text box. Instead of this, I am thinking I can implement a JS random array value picker, which I’ve made already and works fine. However, I want to change the text on it frontend to use the value it selects (a variable). How can I implement this?
Just in case you’re wondering, it’s a text box on the homepage designed to show a random fun fact from my list.
$w(“#nameofyourtextelementgoeshere”).text = variable
Interesting, I just finished added a fun fact box to my home page which picks an image and the associates fact from it.
My database named factsdb has two fields, one text named facttext and one image named factimage. It will count the number of items in the database and then pick a random number from that range which ultimately determines the record to be displayed.
Note: I got the random code from someone else in this forum, I wish I could recall who exactly but figured I would share my code.
Hope this helps.
import wixWindow from ‘wix-window’;
import wixData from ‘wix-data’;
// ====== THIS CODE IS THE RANDOM FACTS GENERATOR
$w.onReady( async function () {
// Check the render env so this is just done once.
// Otherwise, server-side will render, and then the image
// switches to the image that the client-side rendered.
if (wixWindow.rendering.env === ‘browser’ || wixWindow.viewMode === ‘Preview’) {
let res = await wixData.query(‘factsdb’).find();
let items = res.items;
let count = items.length; // how many images do we have?
let rnd = Math.floor(Math.random() * count);
$w("#irandomimage").src = items[rnd].factimage
$w('#irandomfact').text = items[rnd].facttext
console.log = count
}
});
// ====== END RANDOM FACT GENERATOR CODE
Interesting. Let me know how that works out for you.