Skip to content

Instantly share code, notes, and snippets.

@swaters86
Created August 26, 2014 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save swaters86/609c27a95ea87a4ad7f1 to your computer and use it in GitHub Desktop.
Save swaters86/609c27a95ea87a4ad7f1 to your computer and use it in GitHub Desktop.
Randomize List Using jQuery and remove all items after the 4th item in the list.
<!doctype html>
<html>
<head>
<title>Randomize List Using jQuery</title>
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
<style type="text/css">
.list {
width:600px;
margin:0 auto;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
// This randomizer plugin is from: http://stackoverflow.com/questions/1533910/randomize-a-sequence-of-div-elements-with-jquery
$(".mylist").randomize("li");
});
(function ($) {
$.fn.randomize = function (childElem) {
return this.each(function () {
var $this = $(this);
var elems = $this.children(childElem);
elems.sort(function () {
return (Math.round(Math.random()) - 0.5);
});
$this.remove(childElem);
for (var i = 0; i < elems.length; i++)
$this.append(elems[i]);
});
};
})(jQuery);
$(document).ready(function () {
$("li").each(function (i) {
if (i > 3) {
$(this).remove();
}
});
});
</script>
<head>
<body>
<ul class="mylist">
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
<li>list item 6</li>
<li>list item 7</li>
<li>list item 8</li>
<li>list item 9</li>
<li>list item 10</li>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment