Skip to content

Instantly share code, notes, and snippets.

@cauerego
Created March 16, 2011 20:55
Show Gist options
  • Save cauerego/873282 to your computer and use it in GitHub Desktop.
Save cauerego/873282 to your computer and use it in GitHub Desktop.
fork from jsbin to randomize elements - try: http://jsbin.com/gist/873282#preview ( originally at http://jsbin.com/oyaxa/20/edit )
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="jquery.randomize.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
</style>
</head>
<body>
<div class="band">
<table>
<tr><td>
<div class="member">
<ul>
<li>John</li>
<li>Lennon</li>
</ul>
</div>
</td></tr>
<tr><td>
<div class="member">
<ul>
<li>Paul</li>
<li>McCartney</li>
</ul>
</div>
</td></tr>
<tr><td>
<div class="member">
<ul>
<li>George</li>
<li>Harrison</li>
</ul>
</div>
</td></tr>
<tr><td>
<div class="member">
<ul>
<li>Ringo</li>
<li>Starr</li>
</ul>
</div>
</td></tr>
</table>
</div>
<button>Randomize</button>
</body>
</html>
// script adapted from http://jsbin.com/oyaxa/edit originally credited to WEBSITEDESIGNERNC.COM and said to be based on: http://plugins.jquery.com/project/jQuiz
$('button').click(function() {
$("div.band").randomize("table tr td", "div.member");
});
(function($) {
$.fn.randomize = function(tree, childElem) {
return this.each(function() {
var $this = $(this);
if (tree) $this = $(this).find(tree);
var unsortedElems = $this.children(childElem);
var elems = unsortedElems.clone();
elems.sort(function() { return (Math.round(Math.random())-0.5); });
for(var i=0; i < elems.length; i++)
unsortedElems.eq(i).replaceWith(elems[i]);
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment