user4630
user4630

Reputation: 633

Add same random class on refresh to multiple elements?

After a random class being added to elements and it changing on each refresh.

The following works, but i need it to be the same class for each element not random within it.

var classes = ["yellow", "pink", "green"];

$("body,#container,.site-header").each(function(){
    $(this).addClass(classes[~~(Math.random()*classes.length)]);
});

The class is added to body, #container and .site-header as it should, but they are all different ones.

So... body, #container and .site-header should all have yellow, or all have pink etc changing on refresh.

body.pink
#container.pink
.site-header.pink

Currently body will have yellow, #container pink etc which is not what i’m after see...

body.pink
#container.yellow
.site-header.green

Upvotes: 1

Views: 725

Answers (1)

user4630
user4630

Reputation: 633

I’ve figured it out myself, if anyone needs it..

var classes = ['purple','green', 'yellow', 'pink'];
var randomnumber = Math.floor(Math.random()*classes.length);

$('body,#container,.site-header').addClass(classes[randomnumber]);  

Upvotes: 3

Related Questions