Display X divs randomly out of a possible Y.
Posted
by Jordan
on Stack Overflow
See other posts from Stack Overflow
or by Jordan
Published on 2010-03-23T05:25:06Z
Indexed on
2010/03/23
5:33 UTC
Read the original article
Hit count: 263
How do I randomly display 3 divs out of a possible 10 in total?
This is what I have tried so far:
HTML:
<div id="1">Content 1</div>
<div id="2">Content 2</div>
<div id="3">Content 3</div>
<div id="4">Content 4</div>
<div id="5">Content 5</div>
<div id="6">Content 6</div>
Javascript:
function randomiseDiv()
{
// Define how many divs we have
var divCount = 6;
// Get our random ID (based on the total above)
var randomId = Math.floor(Math.random()*divCount+1);
// Get the div that's been randomly selectted
var chosenDiv= document.getElementById(randomId);
// If the content is available on the page
if (chosenDiv)
{
// Update the display
chosenDiv.style.display = 'block';
}
}
window.onload = randomiseDiv;
I would prefer a PHP solution, although anything at this stage would be beneficial.
© Stack Overflow or respective owner