4

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?

1

3 Answers 3

8

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));
       }
Sign up to request clarification or add additional context in comments.

Comments

1

Actually it's pretty simple:

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

That's it! Enjoy.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.