Skip to content

Instantly share code, notes, and snippets.

@artpolikarpov
Created July 20, 2013 10:19
Show Gist options
  • Save artpolikarpov/6044567 to your computer and use it in GitHub Desktop.
Save artpolikarpov/6044567 to your computer and use it in GitHub Desktop.
$.fn.shuffleChildren
(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);
@mistakster
Copy link

If the elements don't have to be well mixed, you can use one line function:

// $ele — root element
$ele.children().sort(function () { return Math.random() - 0.5; }).appendTo($ele);

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment