Alexandru Vlas Alexandru Vlas - 1 year ago 64
HTML Question

How to show 3 random item of list using jquery?

I have a big list

of items and a button to "shuffle" the list, what I'm trying to achieve is, show only 3 RANDOM list items when the page loads, then on button click, shuffle the list, hide the current 3 list items and show OTHER RANDOM list items.

What I did till now is this, but it doesn't really do everything I'm trying to achieve, I get 3 items showed only, but they get randomised between the same 3 list items always...

$('.fr_revs > li').hide().filter(':lt(3)').show();

var ul = document.querySelector('.fr_revs');
for (var i = ul.children.length; i >= 0; i--) {
ul.appendChild(ul.children[Math.random() * i | 0]);

Can somebody help me please. Thank you

Answer Source

Try something like this

var ul = $('ul'),
    lis = ul.find('li').detach(),
    button = $('#shuffle'),
    used = [];

function showRandom() {
    var new_lis = [];
    while (true) {
      var li = lis[Math.floor(Math.random() * lis.length)];
      if (used.indexOf(li) === -1 && new_lis.indexOf(li) === -1) new_lis.push(li);
      if (new_lis.length >= 3) break;
    used = new_lis;

You need to have six or more <li> elements, otherwise it will be an infinite while (true) loop.