jquery move elements into a random order
After much exploration, I decided to take the fisher-yates algorithm and apply it with jquery without requiring cloning, etc.
$('#tout4 img.img_lg').shuffle();
/*
* Shuffle jQuery array of elements - see Fisher-Yates algorithm
*/
jQuery.fn.shuffle = function () {
var j;
for (var i = 0; i < this.length; i++) {
j = Math.floor(Math.random() * this.length);
$(this[i]).before($(this[j]));
}
return this;
};
You can also use the common JavaScript Array randomize sorter, also commented here and here:
$('<my selector>').sort( function(){ return ( Math.round( Math.random() ) - 0.5 ) } );
Ended up using this (thanks Blair!) -
/**
* jQuery Shuffle (/web/20120307220753/http://mktgdept.com/jquery-shuffle)
* A jQuery plugin for shuffling a set of elements
*
* v0.0.1 - 13 November 2009
*
* Copyright (c) 2009 Chad Smith (/web/20120307220753/http://twitter.com/chadsmith)
* Dual licensed under the MIT and GPL licenses.
* /web/20120307220753/http://www.opensource.org/licenses/mit-license.php
* /web/20120307220753/http://www.opensource.org/licenses/gpl-license.php
*
* Shuffle elements using: $(selector).shuffle() or $.shuffle(selector)
*
**/
(function(d){d.fn.shuffle=function(c){c=[];return this.each(function(){c.push(d(this).clone(true))}).each(function(a,b){d(b).replaceWith(c[a=Math.floor(Math.random()*c.length)]);c.splice(a,1)})};d.shuffle=function(a){return d(a).shuffle()}})(jQuery);
So then the only additions that need to be made to the above code are to include the script, and call the shuffle function:
<script type="text/javascript" src="js/jquery-shuffle.js"></script>
$('#tout4 img.img_lg').shuffle();