Shuffle DOM Elements
This is from James Padolsey. Check out his article for a pure JavaScript technique as well.
Plugin
(function($){
$.fn.shuffle = function() {
var allElems = this.get(),
getRandom = function(max) {
return Math.floor(Math.random() * max);
},
shuffled = $.map(allElems, function(){
var random = getRandom(allElems.length),
randEl = $(allElems[random]).clone(true)[0];
allElems.splice(random, 1);
return randEl;
});
this.each(function(i){
$(this).replaceWith($(shuffled[i]));
});
return $(shuffled);
};
})(jQuery);
Usage
Target elements, call shuffle.
$('ul#list li').shuffle();
Thank you for this post – it’s useful. I’m going to read again jQuery docs about map, get and replaceWith, and about native js splice as well.
Your web design is awesome. I love it. Congratulations!
Alex
Great piece. Thank You.
Great plugin. Thanks a million.
Anyone have an idea how to make this work if you want to randomize say two different lists on the same page? Yes I could assign a different ID to each list then suffle them like so:
$(‘ul#list1 li’).shuffle();
$(‘ul#list2 li’).shuffle();
But what I’d like to be able to do is just go:
$(‘ul.randlist li’).shuffle();
And that would then randomize just the list items within that UL, even if I had multiple lists on a page. Right now what it does it randomizes all the list items across ALL the ul’s with that class. Which is not what I want as the list items need to stay with their parent.
Trevor, this is simple using
each()$('ul.randlist').each(function(){$(this).find('li').shuffle()
})
Also, I noticed that this plugin will break references to the original elements (since it actually copies them). I wrote a version that actually shuffles the original elements.
“`
(function($){
})(jQuery)
“`
Excellent tip! I would just add that if you have nested list items (ul ul li) within your parent ul#list, in order to only randomize the parent list items, use this code to initialize: