Skip to content Skip to sidebar Skip to footer

How To Generate A Random Id For Body Tag Upon Page Load Using A Set Array Of Ids

Here's my issue: I have a very simple html website teaser right now with a large background image (www.iambold.org). The background image is set up on the body tag, and so is the b

Solution 1:

  1. Store the possible IDs in a list (array).
  2. Generate a random integer using Math.random() and Math.floor().
  3. Pick the element from the list.
  4. Set the id attribute to the element's value.

Example (no jQuery needed for this simple script):

$(function(){ //<-- That's jQuery, because `document.body` does not exist// in the head of the document.var styleIds = ["body1", "body2"];
    document.body.id = styleIds[ Math.floor(Math.random()*styleIds.length) ];
});

The Math.random() method returns a random number satisfying 0 <= x < 1. Math.floor floors the number. With a list size of 2, the possible numbers are: 0 and 1, which is what we want, because indexes of arrays are zero-based.

Solution 2:

var ids = ['body_1', 'body_2', 'body_3'];
$(function () {
    $('body').attr('id', ids[Math.floor(Math.random()*ids.length)])
});

Demo

if you keep you css declarations constant, just put this at the bottom of you page

<script>document.body.id = "body_" + Math.floor(Math.random()*[NUMBER_OF_DECLARATIONS]); </script></body>

Solution 3:

I would use simple classes instead of ID selectors in your CSS. So define several classes in CSS then use the following snippet to assign a random class.

var classes = [ "classBg1", "classBg2", "classBg3" ];

$.ready( function() {
    var nextClass = classes[ Math.round( classes.length * Math.random() ) ];
    $('body').addClass( nextClass );
});

Solution 4:

You'll need to create an array with valid ids and then grab a random element from it.

Solution 5:

You can use Math.random() to generate a random no. between 0 and 1. Then you can Math.floor() to take the nearest no. and then assign this to your body tags and have them pick one based on what is generated by Math.random() functions

Post a Comment for "How To Generate A Random Id For Body Tag Upon Page Load Using A Set Array Of Ids"