Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly sort list items?

I currently have this code that randomly sorts list items:

var $ul = $('#some-ul-id');
$('li', $ul).sort(function(){
   return ( Math.round( Math.random() ) - 0.5 )
}).appendTo($ul);

However, is there any better solution for that?

like image 902
Ivan Avatar asked Jan 28 '13 04:01

Ivan


1 Answers

Look at this question and answer thread. I like this solution via the user gruppler:

$.fn.randomize = function(selector){
    var $elems = selector ? $(this).find(selector) : $(this).children(),
        $parents = $elems.parent();

    $parents.each(function(){
        $(this).children(selector).sort(function(){
            return Math.round(Math.random()) - 0.5;
        // }). remove().appendTo(this); // 2014-05-24: Removed `random` but leaving for reference. See notes under 'ANOTHER EDIT'
        }).detach().appendTo(this);
    });

    return this;
};

EDIT: Usage instructions below.

To randomize all <li> elements within each '.member' <div>:

$('.member').randomize('li');

To randomize all children of each <ul>:

$('ul').randomize();

ANOTHER EDIT: akalata has let me know in the comments that detach() can be used instead of remove() with the main benefit being if any data or attached listeners are connected to an element and they are randomized, detach() will keep them in place. remove() would just toss the listeners out.

like image 153
Giacomo1968 Avatar answered Sep 28 '22 18:09

Giacomo1968