views:

62

answers:

3

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.

+1  A: 

Based on the anwser to this question : http://stackoverflow.com/questions/2380019/generate-8-unique-random-numbers-between-1-and-100/2380349#2380349, here is how you can pick n unique members in an array :

// removes n random elements from array this
// and returns them
Array.prototype.pick = function(n) {
    if(!n || !this.length) return [];
    var i = Math.floor(this.length*Math.random());
    return this.splice(i,1).concat(this.pick(n-1));
}

So you can apply it to pick 3 divs out of your collection and display them:

 // build the collection of divs with your framework of choice
 // jQuery would be $('div'), Mootools/Prototype $$('div')
var divs = document.getElementsByTagName('div');
// then pick 3 unique random divs and display them
// each is part of ECMAscript5 and a number of current js frameworks
divs.pick(3).each(function (div) {
  div.style.display = "block";
});
// Prototype shortcut is divs.pick(3).invoke('show'); 
Alsciende
LOL - I saw the title of this question and thought that it was similar to the question that we helped with last week. Opened up the question and found the same person answering this one. :-)
belugabob
Had to respond to the call of Randomness ;-) And in the process I demonstrated the usefulness of extending the builtin prototypes ;)
Alsciende
A: 

If you are looking for a PHP way, you could try this assuming $div is an array containing the 6 elements.

for($i = 1; $i <= 3; $i++) {
    $div_num = mt_rand(1,6);
    echo $div[$div_num];
}
Jamza
+1  A: 

You could have the possible div contents in an array, say, $divs, and pick three like this:

$divs = array("Content 1", "Content 2", "Content 3");

for($i = 1; $i <= 3; $i++) {
    shuffle($divs);
    $pick = array_pop($divs);
    echo "<div>$pick</div>";
}

You should also add some kind of error check to see if there is at least 3 values in the array.

Another possible solution is to use array_rand.

oli