Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rionmonster/e8a4bfb3c83d87744e197753f144f2fe to your computer and use it in GitHub Desktop.
Save rionmonster/e8a4bfb3c83d87744e197753f144f2fe to your computer and use it in GitHub Desktop.
// This indicates that this function is going to extend from jQuery
// and it accepts a jQuery selector as a parameter
$.fn.randomize = function(selector){
// This will attempt to find a selector if one exists (this.find(selector)) or it will use the current object (this)
// And it will target the parent of whatever is selected
(selector ? this.find(selector) : this).parent().each(function(){
// It will then target all of the children below this selector and sort each of them based off of a randomly generated value
// from Math.random(). This will apply the order to the elements
$(this).children(selector).sort(function(){
return Math.random() - 0.5;
})
// Each of the elements will then be detached from the DOM and...
.detach()
// Then reappended using the new order
.appendTo(this);
});
// This returns the object to support chaining calls in jQuery
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment