Monday, July 18, 2022

[FIXED] How to randomize the value of class on body tag?

Issue

I have an array with some strings and I choose a random one. I need this value on <body class="MY_STRING">. How can I do this?

I tried something like:

document.write('<body class="' + my_string + '">')

but didn't work.

Update: The question is misconceived. My doubt was not about random elements. This question explains better (and contais the answer that i need):

Setting document.body.className as a variable

I did not knew how to explain the problem. Ty for answers.


Solution

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var classes = ['green', 'red', 'blue', 'black', 'purple'],
    randomClass = classes[getRandomInt(0, classes.length - 1)];

document.body.className = randomClass;

Fiddle: http://jsfiddle.net/PQ9J3/2/



Answered By - Dominic
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.