Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  187] [ 5]  / answers: 1 / hits: 43947  / 13 Years ago, mon, august 15, 2011, 12:00:00

I have a list:



<ul>
<li>milk</li>
<li>butter</li>
<li>eggs</li>
<li>orange juice</li>
<li>bananas</li>
</ul>


Using javascript how can I reorder the list items randomly?


More From » html

 Answers
41
var ul = document.querySelector('ul');
for (var i = ul.children.length; i >= 0; i--) {
ul.appendChild(ul.children[Math.random() * i | 0]);
}


This is based on Fisher–Yates shuffle, and exploits the fact that when you append a node, it's moved from its old place.



Performance is within 10% of shuffling a detached copy even on huge lists (100 000 elements).



http://jsfiddle.net/qEM8B/


[#90597] Sunday, August 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aden

Total Points: 369
Total Questions: 100
Total Answers: 83

Location: Australia
Member since Tue, Oct 19, 2021
3 Years ago
;