Random sorting of filtered gallery

I’m trying to randomize the sorting of a gallery linked to a dataset. I have buttons set up that filter the gallery based on a ‘category’ field, but I would like the images to populate the gallery in a random order. How can I accomplish this?

1 Like

From the top of my head: Tal answered this question ages ago, with example code. Do a search and see what you can find.

I did find some related answers by Tal, but nothing that quite solved this issue…

1 Like

Hi,
Modify this code to match your site:

$w.onReady(function () {
    $w("#dataset1").onReady(() => {
       let items = $w("#gallery1").items;
       items = shuffle(items);
       $w("#gallery1").items = items;
    });
});
export function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
   const j = Math.floor(Math.random() * (i + 1));
   [array[i], array[j]] = [array[j], array[i]];
}

return array;
}

Good luck :slight_smile:

2 Likes

Hi.
Thanks for code. It looks like it works, but I use some filters in code, which made by watching tutorials (have no knowledge in coding though).
Could you, please, help me to adapt that randomization option to my code that could work with filters?
So basically my code looks like:

 // For full API documentation, including code examples, visit https://wix.to/94BuAAs

import wixData from 'wix-data';

$w.onReady(function () {
 //TODO: write your page related code here...

});

// HOUSES filter
export function HousesButton_onClick() {
    console.log("filtering items to HOUSES");

    $w("#myCollection").setFilter( wixData.filter().contains('type', 'house') )
 
        .catch((error) => {
 let errorMsg = error.message;
 let code = error.code;
        });
}


// ALL PROJECTS aka clear filters
export function allProjects_onClick() {
    console.log("attempting to clear filters")
    $w("#myCollection").setFilter ( wixData.filter())
    .then(() => {
console.log("dataset filters have bean cleared");
    })
 
    .catch((error) => {
 let errorMsg = error.message;
 let code = error.code;
        });
}

$w.onReady(function () {
    $w("#myCollection").onReady(() => {
 let items = $w("#gallery1").items;
       items = shuffle(items);
       $w("#gallery1").items = items;
    });
});
export function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
 const j = Math.floor(Math.random() * (i + 1));
   [array[i], array[j]] = [array[j], array[i]];
}

return array;
}