I want my website’s header image to change each time the visitor refreshes the page. I have 23 images in a dataset to choose from.
I have borrowed some code from another discussion but I am having some trouble - the image is in a repeater, and i’ve specified in the dataset settings to display only 1 image at a time.
However, when I run the code, it displays all images from the collection in a random order. My guess is the code interferes with the dataset settings.
Any help?
Here is the code:
import wixData from ‘wix-data’ ;
$w . onReady ( function () {
$w ( “#dataset1” ). onReady (() => {
wixData . query ( “WebIcon” )
. find ()
. then (( result ) => {
const shuffledArray = shuffleArray ( result . items );
$w ( ‘#repeater1’ ). data = shuffledArray ;
})
. catch (( err ) => {
let errorMsg = err ;
});
});
});
function getRandomIndex ( min , max ) {
return Math . round ( Math . random () * ( max - min ) + min );
}
function shuffleArray ( dataArray ) {
**for** ( let i = dataArray . length - 1 ; i > 0 ; i --) {
let index = getRandomIndex ( 0 , i );
const temp = dataArray [ i ];
dataArray [ i ] = dataArray [ index ];
dataArray [ index ] = temp ;
}
**return** dataArray ;
}
Borrowed from this discussion here: https://community.wix.com/velo/forum/coding-with-velo/display-random-image-from-collection