How to change background-color every time the page refreshes? - Javascript

Asked

Viewed 55 times

1

How can I do a function with Javascript that: whenever you refresh the page, change the background-color tag body to one of the default colors? Example: I want to define a 3 different colors, so that whenever the page is updated, change to one of these 3 colors randomly, and this happens whenever the page is updated. I don’t know how to do that function, so far what I have is this:

function mudarCores() {
    document.body.style.background = "#FF00FF";
}
  • Like I would: Put an id on the body. Save the possible colors inside an array. I would use the Math.Random function to select one of these colors. Then I would use getElementById('idDoBody).style.background = Corescolhida. Tell me if it worked

2 answers

0

One way to do this is to record the color information in the localStorage of the browser and on onLoad of the page, read this information and change the color based on it.

Example:

//Evento de onload, será quando a página for acessada ou sofrer uma atualização
window.onload = function(){
  //Pego a cor no localStorage
  let color = localStorage.getItem("color");

  //Índice de busca da cor
  let indexColor = 0;

  //Paleta de cores pré-definidas
  let colors = ["#FF00FF", "#464131", "#269486"];

  //Se a cor não estiver nula, já existe algum no localStorage, então usamos ela
  //caso contrário, começa em zero, conforme o indexColor declaro anteriormente
  if (color != null) {
    indexColor = parseInt(color);
  }

  //Seto a cor de fundo
  document.body.style.backgroundColor = colors[indexColor];

  //Incremento a cor para mudar no próximo carregamento
  indexColor++;

  //Se a cor estiver do tamanho do array, preciso recomeçar a contagem
  //caso contrário, posso acessar uma posição inválida do array
  if (indexColor === colors.length) {
    indexColor = 0;    
  }

  //Gravo no localStorage o índice da próxima cor que será usada
  localStorage.setItem("color", indexColor.toString());
}

Documentations:

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage https://developer.mozilla.org/en-US/docs/Web/API/Storage

0

Every time the document loads select a color randomly.

const cores = ['black', 'red', 'navy'];

window.addEventListener('load', function() {
  document.body.style.backgroundColor = cores[Math.floor(Math.random() * cores.length)]
});

Event load.
Object window.

Browser other questions tagged

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