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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With