How to make a script that generates a random background color on the site?

0

Here's my code, I do not know what's wrong:

var x = Math.random();

if (x < 0.5) {
  document.getElementsByTagName('body').style.backgroundColor = "lightgrey";
} else {
  document.getElementsByTagName('body').style.backgroundColor = "dodgerblue";
}
    
asked by anonymous 10.07.2017 / 23:18

2 answers

2

The getElementsByTagName function returns a list with all elements body of the document, so you need to define which element you want to handle. In this case, being the element body , there will only be one, then just do:

document.getElementsByTagName('body')[0]

Looking like this:

var x = Math.random();

if (x < 0.5) {
  document.getElementsByTagName('body')[0].style.backgroundColor = "lightgrey";
} else {
  document.getElementsByTagName('body')[0].style.backgroundColor = "dodgerblue";
}

But, easier than that, you can only do document.body , without using getElementsByTagName . See the example below:

var x = Math.random();

if (x < 0.5) {
  document.body.style.backgroundColor = "lightgrey";
} else {
  document.body.style.backgroundColor = "dodgerblue";
}
    
10.07.2017 / 23:26
1

Notice that the function used is in the plural getElementsByTagName and therefore returns an array of elements instead of an element. You can change your code to assign the color to element 0 which will be the first and only one doing:

document.getElementsByTagName('body')[0]

Example:

var x = Math.random();
if (x < 0.5) {
	document.getElementsByTagName('body')[0].style.backgroundColor = "lightgrey";
} 
else {
	document.getElementsByTagName('body')[0].style.backgroundColor = "dodgerblue";
}

Alternatively you can even generate a completely random color if you want, making use of rgb in the color assignment in the form of:

rgb(vermelho, verde, azul)

Where each of the color parts goes from 0 to 255, 0 being empty and 255 being full.

var vermelho = Math.round(Math.random()*255); //criar um numero de 0 a 255 e arredondar
var verde = Math.round(Math.random()*255);
var azul = Math.round(Math.random()*255);

document.getElementsByTagName('body')[0].style.backgroundColor = "rgb(" + vermelho + "," + verde + "," + azul + ")";
    
10.07.2017 / 23:24