Streaming live at 10am (PST)

Showing one random collection item on refresh (bypassing the 12 hour CDN server refresh)

Hi everyone,

I’ve been looking for a way to show one random collection item on every refresh.
@Waldo helped me in the right direction with this great piece of code to shuffle the order of items on every refresh. [CMS] Random sorting

Unfortunately this code works with the posts available after the ‘Limit items’ was applied. So when you limited the amount of items to show to just one, you would just see the first collection item on refresh.

To solve this, I found the code below. You just add it to your page next to Waldo’s code and change the class name to the same one used in his code.

$(document).ready(function() {
		var show_limit = 1;
$('.listitemclassname').each(function(){
  if (   $(this).index() >= show_limit) {
     $(this).addClass('hidden-list-item');
       
    }
});
});

Now you can refresh the page > Webflow will load all collection items > Waldo’s code will shuffle them > my code will hide all items, but one.

Hope this will help someone!

Edit: I forgot to add the custom css below.

.hidden-list-item { display: none; }

2 Likes

Let me know if I can get you a beer :+1: :+1: :+1:

1 Like

Hi there,

I’m trying this out but am not sure if I’ve pasted it in the correct spot and position with Waldo’s code (it isn’t working for me). Could you check the below for me please?

If the code is correct then maybe it is an issue with my class name? I named both the collection list with a class name and the collection list items with a class name and tried both but neither worked…

Thanks in advance for your help!

Hmm… I can’t see anything wrong with your code. The class name should be the collection-item indeed.Did you also include the custom css?

.hidden-list-item { display: none; }

EDIT:

Give this a try, then you don’t need the css.

var cards = $(".ArchImages");
for(var i = 0; i < cards.length; i++){
    var target = Math.floor(Math.random() * cards.length -1) + 1;
    var target2 = Math.floor(Math.random() * cards.length -1) +1;
    cards.eq(target).before(cards.eq(target2));
    
        
    $( document ).ready(function() {
		var show_limit = 1;
    $('.ArchImages').each(function(){
      if (   $(this).index() >= show_limit) {
         $(this).css("display", "none");
           
        }
    });
});
}

Weblow converts class names to lowercase and adds hyphens on blank spaces on publish so your code should match. Check your code in devtools.

Thanks so much for your help guys, I’ve got it working now! I still had the limit for the CMS list set to show 1 and it stopped it from working.

1 Like