views:

331

answers:

5

Hello, I'm working on a client's HTML based site and need to randomly order a set of Divs on refresh of a page. I would normally handle this through PHP and a database call, but it's a static site.

So, I'm wondering if anyone knows how to randomly display a set of div's using jquery?

Here's an example:

<div class="myItems">
     <div class="item">1</div>
     <div class="item">2</div>
     <div class="item">3</div>
</div>

and on refresh, it might change to:

<div class="myItems">
     <div class="item">2</div>
     <div class="item">3</div>
     <div class="item">1</div>
</div>

Anyone know how to do that?

Thanks! Troy

+2  A: 

This may help...

Sarfraz
Thanks Sarfraz!
Troy
@Troy: Welcome :)
Sarfraz
+1  A: 

This willl do it

 function reorder() {
           var grp = $(".myItems").children();
           var cnt = grp.length;

           var temp,x;
           for (var i = 0; i < cnt; i++) {
               temp = grp[i];
             x = Math.floor(Math.random() * cnt);
             grp[i] = grp[x];
             grp[x] = temp;
         }
         $(grp).remove();
         $(".myItems").append($(grp));
       }
josephj1989
+1: That's nicely done :)
Sarfraz
That worked Beautifully! Thanks Joseph!!!!
Troy
A: 

Another simple way is ... 1. create an array 2. generate a random number and check if it is Odd or Even 3. If odd, add your div to the top (shift method). If even, add your div to the bottom (push method). 4. So this way you will have your divs arranged randomly in the array. 5. Now simple join the array and append it to your Page.

var divArray = [];

for(var i=0; i<divs.length; i++){
  //generate random number
  if(rand_num == odd)
     divArray.push( div[i] );
  else
     divArray.shift( div[i] );
}

$(myElem).html( divArray.join("") );
Ashit Vora
A: 

Hi,

I have a similiar problem, but in my case the children contain event handlers. Is there an easy way to sort the elements without removing the event handlers?

Thanks in advance. Giel

Giel Van den Broeck