<p>Click to rearrange the list with the Fisher-Yates shuffle.</p>
<ul id="list" class="list-reset p0">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
(function(){
function fyShuffle(array) {
var total = array.length;
var remaining;
var i;
while (total) {
i = Math.floor(Math.random() * total--);
remaining = array[total];
array[total] = array[i];
array[i] = remaining;
}
return array;
}
function makeNewArrayFromChildren(parent) {
var newArray = [];
var children = parent.children;
for (var i = 0; i < children.length; i++) {
newArray.push(children[i]);
}
return newArray;
}
var body = document.getElementsByTagName('body')[0];
var list = document.getElementById('list');
body.addEventListener('click', function(e) {
e.preventDefault();
// Copy children to a temporary array
var newChildren = makeNewArrayFromChildren(list);
// Shuffle the children
var rearranged = fyShuffle(newChildren);
// Create a fragment and append children to it
var fragment = document.createDocumentFragment();
for (var i = 0; i < rearranged.length; i++) {
fragment.appendChild(rearranged[i]);
}
// Reset DOM children and replace with fragment
list.innerHTML = '';
list.appendChild(fragment);
});
})();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.