Skip to content

Instantly share code, notes, and snippets.

@JudeRosario
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JudeRosario/d49fe4d99f4def773de4 to your computer and use it in GitHub Desktop.
Save JudeRosario/d49fe4d99f4def773de4 to your computer and use it in GitHub Desktop.
Randomize DOM
// Explicitly pass the sidebar to the randomizer function
jQuery( document ).ready(function() {
jQuery(".sidebar").randomize("ul", "li");
});
// Explicitly pass what to randomize to the randomizer function
jQuery( document ).ready(function() {
jQuery("#div1").randomize("ul", "li.crop-square");
});
// The Logic to randomize stuff from your DOM
(function($) {
$.fn.randomize = function(tree, childElem) {
return this.each(function() {
var $this = $(this);
if (tree) $this = $(this).find(tree);
var unsortedElems = $this.children(childElem);
var elems = unsortedElems.clone();
elems.sort(function() { return (Math.round(Math.random())-0.5); });
for(var i=0; i < elems.length; i++)
unsortedElems.eq(i).replaceWith(elems[i]);
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment