-1

How do I randomly rearrange the order of div classes shuffledv but keep the id's in the same order every time I refresh the page?

<div class="shuffledv">
<div id="2"></div>
<div id="3"></div>
<div id="1"></div>
</div>
<div class="shuffledv">
<div id="5"></div>
<div id="4"></div>
<div id="6"></div>
</div>
<div class="shuffledv">
<div id="9"></div>
<div id="8"></div>
<div id="7"></div>
</div>
<div class="shuffledv">
<div id="10"></div>
<div id="11"></div>
<div id="12"></div>
</div>
Billy
  • 2,823
  • 3
  • 16
  • 33

1 Answers1

1

I think this is what you're looking for:

elems = $('.shuffledv');

elems = shuffle(elems); //shuffle all the elements.


for (i = 0; i < elems.length; i++) {

  $(elems[i]).appendTo($('.container')); //reinsert.
}

function shuffle(array) { //From COOLAJ86 at http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
  var currentIndex = array.length,
    temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="container">


  <div class="shuffledv">
    first
    <div id="2"></div>
    <div id="3"></div>
    <div id="1"></div>
  </div>

  <div class="shuffledv">
    second
    <div id="5"></div>
    <div id="4"></div>
    <div id="6"></div>
  </div>
  <div class="shuffledv">
    third
    <div id="2"></div>
    <div id="3"></div>
    <div id="1"></div>
  </div>
  <div class="shuffledv">
    fourth
    <div id="5"></div>
    <div id="4"></div>
    <div id="6"></div>
  </div>
</div>

it will shuffle them around everytime it's run. It's best done if they have a container.

Greg Borbonus
  • 1,384
  • 8
  • 16