How to Shuffle Children Elements of HTML dynamically?

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
admin
Site Admin
Posts: 44

How to Shuffle Children Elements of HTML dynamically?

Post by admin » Thu Aug 22, 2019 2:50 pm

HTML:

Code: Select all

<ul class="shuffle">
  <li>This</li>
  <li>Little</li>
  <li>Piggy</li>
  <li>Went</li>
  <li>To</li>
  <li>Market</li>
</ul>

<div class="shuffle">
  <div>This</div>
  <div>Little</div>
  <div>Piggy</div>
  <div>Went</div>
  <div>To</div>
  <div>Market</div>
</div>

<br><br>

<button class="button" id="shuffle">Shuffle Children</button>
CSS:

Code: Select all

body {
  margin: 20px; 
}
div > div {
  display: inline-block;
  background: #26A69A;
  color: white;
  margin: 4px;
  padding: 8px;
  border-radius: 4px;
}
jQuery:

Code: Select all

$.fn.shuffleChildren = function() {
  $.each(this.get(), function(index, el) {
    var $el = $(el);
    var $find = $el.children();

    $find.sort(function() {
      return 0.5 - Math.random();
    });

    $el.empty();
    $find.appendTo($el);
  });
};

$("#shuffle").click(function() {
  // Usage
  $(".shuffle").shuffleChildren();
});

Post Reply