Last active
August 29, 2015 14:23
-
-
Save twoblokeswithapostie/84b43f046c9099a57ce7 to your computer and use it in GitHub Desktop.
jQuery DOM element shuffler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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