Randomly Sort Anything with jQuery
by Ryan Brackett
HTML
<script>
$(document).ready(function() {
$('.random-sort tr').shuffle();
});
</script>
Run the script and watch the table rows sort randomly.
<br/>
<br/>
<table border="0" cellspacing="0" class="random-sort">
<tbody>
<tr>
<td>John</td>
</tr>
<tr>
<td>Bill</td>
</tr>
<tr>
<td class="red">Jenna</td>
</tr>
<tr>
<td>Brooke</td>
</tr>
<tr>
<td>Peyton</td>
</tr>
</tbody>
</table>
<br/>
<a href="javascript:history.go(0)">Reload the page</a>
CSS
body {
font-family: 'Open Sans', Arial;
padding: 30px;
font-size: 13px;
}
table {
width: 100%;
}
table td {
padding: 15px;
border: 1px solid #ccc;
}
table td.red {
color: white;
background: #fd584c;
}
JavaScript
(function($) {
$.fn.shuffle = function() {
var allElems = this.get(),
getRandom = function(max) {
return Math.floor(Math.random() * max);
},
shuffled = $.map(allElems, function() {
var random = getRandom(allElems.length),
randEl = $(allElems[random]).clone(true)[0];
allElems.splice(random, 1);
return randEl;
});
this.each(function(i) {
$(this).replaceWith($(shuffled[i]));
});
return $(shuffled);
};
})(jQuery);