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.


Recent Comments