I have seemingly easy need but I cannot realize it on my website.
There is a set of text strings - about 10 variations of the slogan - and I need a random one to appear when the page is opened or refreshed. Is there any app or script or default mean for this?
I was planning to do something like this in the future, so I decided to spend some time on it now. Using the getSeconds function and dividing the result by 6 along with the ceil function provides enough randomness for this purpose. The example below has an array of the ten slogans and then references it by index number. Alternately, you could have the slogans in a collection and query them.
let d = new Date(); let n = d.getSeconds(); let slogannum = Math.ceil(n/6); if (slogannum === 0){
slogannum = 1;
}
console.log("Slogan : " + slogannum);
console.log("Slogan name: " + sloganarray[slogannum-1]);
Another approach is to use array[Math.floor(Math.random(numElements))] where array[] is the array of strings and numElements is the # of elements in the array.
Sarabura, that is simpler with fewer lines of code. Since the random function returns a number between 0 and 1, it needs to be multiplied by 10 to be able to return one of the slogans from the array.
Hi guys! Thanks a lot for code, I see how it works!
Though, I’m complete newbie with coding on Wix. Where should I put the code on the page? I’ve switched on Code feature on Wix. I have a slogan text field here… could you help with next step?
You have some reading to do, buddy. We can hold your hand through the process but in the long run you’re better off reading this documentation: Velo: Working in the Code Panel | Help Center | Wix.com plus other topics in the area. That said, I suspect you are looking for the control that I’ve highlighted in the screen shot below, in the lower right corner of the screen.
Thanks! Yes, I’ve found that window already and even figured out that I should probably start with
$w(‘#text33’).onViewPort() where #text33 is my text element.
But could advice where should I put Let expression? I tried it in the parenthesis, and I also tried to add .Call(), but it didn’t work out. Sorry for silly questions
Ok, everything is fine now apart from the fact that code below is triggered twice: at the start of page loading and when everything is loaded. Although onReady presumably should work only when everything is loaded - and only once. Am I mistaken?
Without seeing all of your code, it’s difficult to guess why it’s doing that. You could set the text to be hidden on load, and then show it at the end of the onReady function with the following: