Troy
Troy

Reputation: 971

Change DIV order with jquery

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?

Upvotes: 4

Views: 13412

Answers (3)

Slavik Meltser
Slavik Meltser

Reputation: 10361

Actually it's pretty simple:

$(".myItems").html($(".myItems .item").sort(function(){
    return Math.random()-0.5;
}));

That's it! Enjoy.

Upvotes: 1

Ashit Vora
Ashit Vora

Reputation: 2922

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("") );

Upvotes: 0

josephj1989
josephj1989

Reputation: 9709

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));
       }

Upvotes: 8

Related Questions