jQuery: Shuffle Plugin
I recently came across a really compact array shuffling function on JSFromHell.com, which I thought would make a nifty jQuery plugin.
This jQuery shuffle plugin could be applied to any HTML element or Array object.
(function($){ $.fn.shuffle = function() { return this.each(function(){ var items = $(this).children(); return (items.length) ? $(this).html($.shuffle(items)) : this; }); } $.shuffle = function(arr) { for( var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x ); return arr; } })(jQuery);
Due to line wrapping issues in this post I inserted a few hard carriage returns in the above snippet (sorry).
Example 1: shuffle an unordered list
$('ul').shuffle();
Example 2: shuffle an array
var arr = [1,2,3,4,5,6]; arr = $.shuffle(arr);
There is a demo here. And for those interested I encourage you to download the plugin for closer inspection.


By Raphael Martins at 21 Oct 2008 9:24 pm PDT
By Mike B. at 21 Nov 2008 2:46 pm PST
By Elle at 17 Jan 2009 1:35 pm PST
By caphun at 18 Jan 2009 2:00 am PST
By Shuffling the DOM - James Padolsey at 5 Feb 2009 6:56 am PST
By Implement Array Shuffling in MooTools at 9 Feb 2009 10:01 pm PST
By Rustam Mester at 28 Apr 2009 2:44 pm PDT
By Manish MISTRY at 13 May 2009 2:48 pm PDT
By Hector Virgen at 7 Jul 2009 5:06 am PDT
By caphun at 10 Jul 2009 3:07 pm PDT
By Ellison at 24 Dec 2009 1:25 pm PST
By bamboolabcode at 1 Feb 2010 1:20 pm PST