1

Possible Duplicate:
javascript - shuffle HTML list element order

After a little bit of help. After something quite simple, but can't seem to find a way of doing it myself.

I've got a dynamic unordered list being generated from some back end code, (not under my control). The list can be anything from 9 tags up to 100+. They are returned in an order, as defined by the backend code. Using jQuery/javascript I would like to be able to randomize the order of the li tags without having any of them repeat.

My my list would currently look something like this:

<ul id="myList">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
  <li>Item 9</li>
</ul>
Community
  • 1
  • 1
Strontium_99
  • 1,771
  • 6
  • 31
  • 52

1 Answers1

6

Exactly what you want to do is described on the jQuery Forums.

$(document).ready(function(){
      $('ul').each(function(){
            // get current ul
            var $ul = $(this);
            // get array of list items in current ul
            var $liArr = $ul.children('li');
            // sort array of list items in current ul randomly
            $liArr.sort(function(a,b){
                  // Get a random number between 0 and 10
                  var temp = parseInt( Math.random()*10 );
                  // Get 1 or 0, whether temp is odd or even
                  var isOddOrEven = temp%2;
                  // Get +1 or -1, whether temp greater or smaller than 5
                  var isPosOrNeg = temp>5 ? 1 : -1;
                  // Return -1, 0, or +1
                  return( isOddOrEven*isPosOrNeg );
            })
            // append list items to ul
            .appendTo($ul);            
      });
});

Example: http://jsbin.com/upuju3/2

Fabian
  • 3,465
  • 4
  • 34
  • 42