Shuffle Demo

UL, Div, Array

by jj_gutierrez

HTML

<table border="1" cellpadding="10" cellspacing="0">
  <tr>
    <th>UL</th>
    <th>DIV container</th>
    <th>Array</th>
  </tr>
  <tr>

    <td>
      <ul>
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
        <li>item 5</li>

        <li>item 6</li>
      </ul>
    </td>
    <td>
      <div id="container">
        <div id=1>1</div>
        <div id=1>2</div>
        <div id=1>3</div>
        <div id=1>4</div>
        <div id=1>5</div>
      </div>
    </td>
    <td>

      <div id="array"></div>
    </td>
  </tr>
  <tr>
    <td>
      <button class="item">Shuffle</button>
    </td>
    <td>
      <button class="div">Shuffle</button>
    </td>
    <td>
      <button class="array">Shuffle</button>
    </td>

  </tr>
</table>

CSS

td {
  padding: 23px;
}

JavaScript

// http://yelotofu.com/labs/jquery/snippets/shuffle/demo.html

jQuery(function($) {
  // unordered list
  $('button.item').click(function() {
    $('ul').shuffle();
  });

  // a series of paragraphs
  $('button.div').click(function() {
    $('#container').shuffle();
  });

  // an array
  var arr = [1, 2, 3, 4, 5, 6];
  $('#array').text(arr.join(', '));
  $('button.array').click(function() {
    arr = $.shuffle(arr);
    $('#array').text(arr.join(', '));
  });
});


(function($) {

  $.fn.shuffle = function() {
    return this.each(function() {
      var items = $(this).children().clone(true);
      return (items.length) ? $(this).html($.shuffle(items)) : this;
    });
  }

  $.shuffle = function(arr) {
    for (var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
    return arr;
  }

})(jQuery);