Created
July 20, 2013 10:19
-
-
Save artpolikarpov/6044567 to your computer and use it in GitHub Desktop.
$.fn.shuffleChildren
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
(function ($) { | |
$.fn.shuffleChildren = function () { | |
return this.each(function () { | |
var $children = $(this).children(), | |
l = $children.length; | |
// Fisher–Yates Shuffle | |
// http://bost.ocks.org/mike/shuffle/ | |
// While there remain elements to shuffle | |
while (l) { | |
// Pick a remaining element | |
var i = Math.floor(Math.random() * l--); | |
// And swap it with the current element | |
var t = $children[l]; | |
$children[l] = $children[i]; | |
$children[i] = t; | |
} | |
// Re-append | |
$children.appendTo(this); | |
}); | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If the elements don't have to be well mixed, you can use one line function:
The main disadvantage of this method, as I said before, is poor randomness. But it still usable if you have to continuously shuffle same elements.