Random strip background on homepage from a collection of images.

Hi,

How would I go about setting a strip background image to be random each time the home page loads from a collection of images.

At the moment I’ve created a database with the images in and linked that to the background image of the stripe. But this just sets the first image as the background all the time.

What code do I need to add to have a random image each time?

I’ve tried various searches and things but the code I’ve tried so far doesn’t seem to work. (Bit new to this wix code)

Thanks

Adam

Hi Adam ,

First, get the images from the dataset, then get its length.
now you can use Math.floor(Math.random() * imagesLength), finally you can display random image.
for more information, here is some links to help you :


Your code should look something like this:

 let results= await wixData.query("ataset").find();
 let images= results.items;
 let count = images.length;
 let randomImageNumber = Math.floor(Math.random() * count);
        $w('#stripColumn').background.src = images[randomImageNumber ].image;   // get a random image
       
    

Hope this helps!
Best,

Mustafa

But how / where would I define the actual location of the images to randomize/display? Ideally a folder with content to be used. I am a little lost when it comes to coding - would highly appreciate a short step-by-step explanation. Thanks!!

await value is wrong when I preview the page with the code. What should I do; Thanks in advance!

Here is the code I hope It would useful for you :
$w.onReady( function () {
// To make this Code work in all of your site pages,
// Move these lines into the the ‘Site Code’ panel on the left

    $w( "#imageX1" ).hide(); 
    $w( "#imageX2" ).hide(); 

let num = Math.floor(Math.random()* 10 )
num = num + 1 ;

if ( num < 5 ){
$w( “#imageX1” ).show();
$w( “#imageX2” ).hide();
console.log( “state1” )
}
else {
$w( “#imageX1” ).hide();
$w( “#imageX2” ).show();
console.log( “state2” )
}
console.log(num)
});

Was this ever answered for you? Thanks.