Here's how I did it (JSFiddle example here: http://jsfiddle.net/LNvqr/2/)
If you use jQuery and have HTML similar to this:
<div>
<ul id="rndList">
<li id="itemOne">one</li>
<li id="itemTwo">two</li>
<li id="itemThree">three</li>
<li id="itemFour">four</li>
<li id="itemFive">five</li>
</ul>
</div>
Then you could simply use .detach to remove and store the array of the <li>
elements.
Next, with a copy of the array, use Math.random()
to generate a (pseudo)random integer between 0 and one less than the size of the array. Use this as the random index to be copied from the original (ordered) list in to the new (randomly-ordered) one.
Remove the randomly-chosen element from the original array on each iteration and choose a new random one until all elements have been re-inserted:
function shuffleList() {
var origList = $("#rndList li").detach();
var newList = origList.clone();
for (var i = 0; i < newList.length; i++) {
//select a random index; the number range will decrease by 1 on each iteration
var randomIndex = randomInt(newList.length - i);
//place the randomly-chosen element into our copy and remove from the original:
newList[i] = origList.splice(randomIndex, 1);
//place the element back into into the HTML
$("#rndList").append(newList[i]);
}
}
function randomInt(maxNum) { //returns a random integer from 0 to maxNum-1
return Math.floor(Math.random() * maxNum);
}