0

I would like to shuffle specific DIVs (based on class) around on each page load.

Note i'm using a Wordpress Theme and as such, do not have full control over HTML structure without changing base themes (which i'm not willing to do)

jfiddle is here.

    $(function() {
  $(".shuffle").each(function() {
    var parent = $(this),
      divs = parent.children().remove();

    while (divs.length) {
      parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
    }
  });
});

Parent DIV class = "shuffle"

Child DIVs class = "shuffle-child"

What am I doing wrong? Apologies for lack of JS experience!!

Am68
  • 1
  • 1
  • 1
    Possible duplicate of [javascript - shuffle HTML list element order](http://stackoverflow.com/questions/7070054/javascript-shuffle-html-list-element-order) – Sam0 Jan 22 '17 at 11:38
  • Also a duplicate of http://stackoverflow.com/questions/14555415/how-to-randomly-sort-list-items – Sam0 Jan 22 '17 at 11:39

1 Answers1

0

For your particular scenario you can use the following, adapted for jQuery from https://stackoverflow.com/a/11972692/2413733 @AlexeyLebedev's answer using the Fischer-Yates Shuffle.

var shuffleKids = $('.shuffle-kids'), // the elements to shuffle
  shuffle = shuffleKids.parent(); // the container div

for (var i = shuffleKids.length; i >= 0; i--) {
  shuffle.append(shuffle.children()[Math.random() * i | 0]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class='shuffle'>
  <div class='shuffle-kids'>milk</div>
  <div class='shuffle-kids'>butter</div>
  <div class='shuffle-kids'>eggs</div>
  <div class='shuffle-kids'>orange juice</div>
  <div class='shuffle-kids'>bananas</div>
</div>
Community
  • 1
  • 1
Sam0
  • 1,459
  • 1
  • 11
  • 13