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

Asked

Viewed 50 times

0

Here’s my code, I don’t 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";
}

2 answers

2


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

document.getElementsByTagName('body')[0]

Thus remaining:

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 just document.body, without using the getElementsByTagName. See the example below:

var x = Math.random();

if (x < 0.5) {
  document.body.style.backgroundColor = "lightgrey";
} else {
  document.body.style.backgroundColor = "dodgerblue";
}

  • Does your latest solution work for any tag??? e.g.: Document.div.style.background...

  • @nelson450 No, just the body.

  • Thanks for the help, I’m beginner in JS

1

Note that the function used is plural getElementsByTagName and therefore returns an array of elements instead of an element. You can change your code to assign color to element 0 which will be the first and only 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 like, making use of rgb in color assignment in the form of:

rgb(vermelho, verde, azul)

Where each of the color parts goes from 0 to 255, being 0 empty and 255 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 + ")";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.