Welcome to WebmasterWorld Guest from 54.221.136.62

Forum Moderators: open

Message Too Old, No Replies

Shuffle a list

     
7:18 pm on Apr 28, 2015 (gmt 0)

Junior Member

joined:Mar 1, 2013
posts: 65
votes: 0


Hi,

Is there any way to randomize display order of a list?

For ex:

<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
</ul>

I guess it is possible with jquery "shuffle()" plugin, however I want it done by JavaScript. Please let me know if it is possible with JS
9:58 pm on Apr 28, 2015 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5012
votes: 23



function shuffle(array) {
var m = array.length, t, i;

// While there remain elements to shuffle…
while (m) {

// Pick a remaining element…
i = Math.floor(Math.random() * m--);

// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}

return array;
}

function shuffleList(ul) {
var nl = ul.getElementsByTagName("li"),
arr = [],
i,
n;

// Copy the nodeList to an array
for (i = 0; n = nl[i]; ++i) {
arr.push(n);
}

// Shuffle the array
shuffle(arr);

// Append the elements back to the ul in shuffled order
for (i = 0; i < arr.length; i++) {
ul.appendChild(arr[i]);
}
}


Given this code, call shuffleList with the <ul> element you want to shuffle.
5:48 am on Apr 29, 2015 (gmt 0)

Junior Member

joined:Mar 1, 2013
posts: 65
votes: 0


Thanks Fotiman! :) It is working fine
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members