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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With