Randomizing Div tags using Java Script
Posted
by
Andrew McNeil
on Stack Overflow
See other posts from Stack Overflow
or by Andrew McNeil
Published on 2011-03-09T23:44:06Z
Indexed on
2011/03/10
0:10 UTC
Read the original article
Hit count: 182
JavaScript
|div
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>
© Stack Overflow or respective owner