Skip to content Skip to sidebar Skip to footer

Display X Divs Randomly Out Of A Possible Y

How do I randomly display 3 divs out of a possible 10 in total? This is what I have tried so far: HTML:
Content 1
Content 2

Solution 1:

Based on the anwser to this question : Generate unique random numbers between 1 and 100, here is how you can pick n unique members in an array :

// removes n random elements from array this// and returns themArray.prototype.pick = function(n) {
    if(!n || !this.length) return [];
    var i = Math.floor(this.length*Math.random());
    returnthis.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'); 

Solution 2:

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.

Solution 3:

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];
}

Post a Comment for "Display X Divs Randomly Out Of A Possible Y"