I’ve looked around and have been able to find a piece of code that does the job but it doesn’t work for all of my tags. I have a total of 8 Div tags that I want to randomize and this piece of code only allows me to randomize 7 of them. If I replace the 7 with an 8 it just shows everything in order. I don’t work with Javascript very often and have hit a road block. Any help is greatly appreciated.
<script type="text/javascript">
$(document).ready(function() {
$(".workPiece").hide();
var elements = $(".workPiece");
var elementCount = elements.size();
var elementsToShow = 7;
var alreadyChoosen = ",";
var i = 0;
while (i < elementsToShow) {
var rand = Math.floor(Math.random() * elementCount);
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
elements.eq(rand).show();
++i;
}
}
});
</script>
To make this work with all elements, you need to actually move the elements themselves around to shuffle them, instead of just randomly hiding some of them.
Here is an example jQuery plugin to do that:
You would call it like so:
You can limit the number of visible children like so:
Here’s a jsFiddle for it.