Shuffle or random for repeater ON CLICK

Hi,
I am aware that shuffle / random has been discussed at length on this forum. However I am new to coding and none of the presented solution quite fit what I need. I am not nimble enough to adapt the code I did find. A lot of the examples were for shuffle on load. I need shuffle on load and then again on click.

The page contains ‘flash cards’ for studying a new language.
When the page loads, I want to display 1 random item (flash card) in the repeater.
I then want the user to be able to click the shuffle button to draw a new card.

Here is the link to the draft page: https://jasminenicolespence.wixsite.com/website-2/flashcardslanding

I saw the following code in another post but I don’t think it’s quite right:

let items ;
function shuffleArray () {
let itemsLength = items . length , lastItem , randomIndex ;
while ( itemsLength ) {
randomIndex = Math . floor ( Math . random () * itemsLength – );
lastItem = items [ itemsLength ];
items [ itemsLength ] = items [ randomIndex ];
items [ randomIndex ] = lastItem ;
}
return items ;
}
$w . onReady ( () => {
$w ( “#dataset1” ). onReady ( () => {
$w ( “#dataset1” ). getItems ( 0 , 1000 )
. then ( ( results ) => {
items = results . items ;
$w ( “#repeater1” ). data = shuffleArray ( items );
})
})
})

2 Likes

After 48 hours of obsessive trying I finally got it to work with Indexes. I used code pasted in the forum by @yisrael :

import wixData from ‘wix-data’ ;

// clear any filters in the dataset
$w ( “#dataset1” ). setFilter ( wixData . filter () );

// get size of collection that is connected to the dataset
let count = $w ( “#dataset1” ). getTotalCount ();

// get random number using the size as the maximum
let idx = Math . floor ( Math . random () * count );

// set the current item index of the dataset
$w ( “#dataset1” ). setCurrentItemIndex ( idx );

I added the on-click action for my shuffle button at the top so full code looks like:

import wixData from ‘wix-data’ ;
export function image2_click(event) {
// Add your code for this event here:

// clear any filters in the dataset
$w( “#dataset1” ).setFilter( wixData.filter() );

// get size of collection that is connected to the dataset
let count = $w( “#dataset1” ).getTotalCount();

// get random number using the size as the maximum
let idx = Math.floor(Math.random() * count- 1 );

// set the current item index of the dataset
$w( “#dataset1” ).setCurrentItemIndex(idx);
}

HOPE THIS HELPS SOMEONE AND THANK YOU TO THE CONTRIBUTORS WHOSE WRITING GUIDED ME ESPECIALLY YISRAEL :slight_smile:

Thank you! +1 +1 +1 +1 +1
@Yisrael and Jasmine, Jasmine and @Yisrael