shuffle DOM element - CJ's blog
by CJ Ramki
HTML
<div class="first page">
<img class="image" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQWieYTSB9-8r_0XbPLsr2RHl1kbJATSw67uD7xRdybwTlSrNgP">
<img class="image" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQVar0tVmZZDwQ8WRonU7WdJCPiwp2zeGGspnGXj9QOuMv5W8EH">
<img class="image" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQclzjwaj0_bpb8GLMWS3lQzvBAvptOjjQKUG-Mt2rk9QbKUtOAXA">
</div>
<div class="first page">
<img class="image" src="http://3.bp.blogspot.com/_RlDIa82EkUE/TIy0X0QtZUI/AAAAAAAABy4/qjy2EHZo7a8/s320/ComedyMeltdown.jpg">
<img class="image" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRWbbmXNqtSzd5O4PTk8icp1WZaAv_O1KYYWP_76bpbRE6Y4kxQ">
<img class="image" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ8HRNNMTuNeixYuV_Nf5o5fCza_BHclSjimgUqm6V0q-GpxyFnAw">
</div>
<input type="button" id="btn" value="Shuffle">
CSS
img {
height:100px;
width:100px;
background:blue;
margin-left:10px;
}
JavaScript
$('#btn').click(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);
};
$('img').shuffle();
});