Does anyone know how I could go about randomising an unordered list each time the page is refreshed?

A jQuery solution would be perfect as I'm already using it for other effects.

Any advice appreciated!

1 answer

o.k.w 2355
2
points
This was chosen as the best answer

There you go:

Javascript using jQuery:

$(document).ready(function() {
 var arrLi = []; // an array to store the list items
 var parent = $('ul'); // get the parent UL
 parent.children().each(function(){ 
    //move the items into the array
    arrLi.push($(this).remove().html());
 });
 var rnd = 0; // declare random variable
 while(arrLi.length>0){
    //generate random number between 0 and array length
    rnd = Math.floor(Math.random()*arrLi.length);
    //move random item into parent UL
    parent.append($('<li>' + arrLi.splice(rnd, 1) + '</li>'));
 }
});

HTML:

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
Answered almost 7 years ago by o.k.w
  • brilliant! many thanks! Warren almost 7 years ago
  • @Warren, not the perfect implementation but glad it works for you :) o.k.w almost 7 years ago