Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@twoblokeswithapostie
Last active August 29, 2015 14:23
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 twoblokeswithapostie/84b43f046c9099a57ce7 to your computer and use it in GitHub Desktop.
Save twoblokeswithapostie/84b43f046c9099a57ce7 to your computer and use it in GitHub Desktop.
jQuery DOM element shuffler
// jQuery shuffle plugin usage $('el').shuffle();
(function($){
$.fn.shuffle = function() {
var elements = this.get();
var copy = [].concat(elements);
var shuffled = [];
var placeholders = [];
// Shuffle the element array
while (copy.length) {
var rand = Math.floor(Math.random() * copy.length)
var element = copy.splice(rand,1)[0];
shuffled.push(element);
}
// replace all elements with a plcaceholder
for (var i = 0; i < elements.length; i++) {
var placeholder = document.createTextNode('');
findAndReplace(elements[i], placeholder);
placeholders.push(placeholder);
}
// replace the placeholders with the shuffled elements
for (var i = 0; i < elements.length; i++) {
findAndReplace(placeholders[i], shuffled[i]);
}
return $(shuffled);
}
function findAndReplace(find, replace) {
find.parentNode.replaceChild(replace, find)
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment