0

thanks in advance for reading this.

I have a set of divs (in a grid) and trying to achieve a random / shuffle order on every page load. Essentially that's not a big deal but the crucial point is that I have a parent div (grid) with several childs (level-1) and these childs have several childs (level-2) again.

With a little jQuery I've accomplished a random order of the level-1 divs on every page load, but I need a random order of the level-2 divs as well.

If the starting order looks like this (for example):
A - B - C
D - E - F
G - H - I

I need a new order like that (for example):
G - A - D
C - F - H
I - B - E

Thank you for every help!

I've made a fiddle: https://jsfiddle.net/tns9qumn/

$(function() {
  var parent = $(".grid");
  var divs = parent.children();
  while (divs.length) {
    parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
  }
});
.level-2 {
  width: 3rem;
  height: 3rem;
  background-color: black;
  margin: .5rem;
  color: white;
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="grid">
  <div class="level-1">
    <div class="level-2">A</div>
    <div class="level-2">B</div>
    <div class="level-2">C</div>
  </div>
  <div class="level-1">
    <div class="level-2">D</div>
    <div class="level-2">E</div>
    <div class="level-2">F</div>
  </div>
  <div class="level-1">
    <div class="level-2">G</div>
    <div class="level-2">H</div>
    <div class="level-2">I</div>
  </div>
</div>
Kheber
  • 317
  • 1
  • 3
  • 13

2 Answers2

2

Not sure, but try this ?

$.fn.randomize = function(a,b) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(a).children(b);
      var len = $this.find(a).eq(0).find(b).length;

      elems.sort(function() { return (Math.round(Math.random())-0.5); });  

      $this.detach(a);  

      for(var i=0; i < elems.length; i++) {
        $this.find(a).eq(i%len).append(elems[i]);
      }

  });    
}

$('.grid').randomize('.level-1','.level-2');

Demo : https://jsfiddle.net/l2aelba/rpnyamnL/

Original by : https://stackoverflow.com/a/1533945/622813

Community
  • 1
  • 1
l2aelba
  • 21,591
  • 22
  • 102
  • 138
-1

you can place all your "level-2" <div>in an array, then shuffle it and recreate the grid.

For a shuffle function you can see here

Community
  • 1
  • 1
Yoplaboom
  • 554
  • 3
  • 13