Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 904
Troy Avatar asked Jan 22 '23 21:01

Troy


1 Answers

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));
       }
like image 157
josephj1989 Avatar answered Jan 30 '23 23:01

josephj1989