Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
how to change background color to multiple colors as an animation using Javascript

I need to make a function that changes the background colour to various colours(as an animation). I have used for loop to change hexadecimal colour code. But only I can see the changing it into one colour.

function changeColors() {
    var colors = 000100;

    for (var i = 0; i < 99999; i++) {
        colors += i;
        var x = (document.body.style.backgroundColor = "#" + colors);
    }
}

changeColors();
body {
    background-color: #80eb80;
}
<html>
    <body></body>
</html>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

function changeHex() {
  let hex = '#';
  const hexValues = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'];
  for (let i = 0; i < 6; i++) {
    const index = Math.floor(Math.random() * hexValues.length);
    hex += hexValues[index];
  }

  document.querySelector('body').style.backgroundColor = hex;
}

setInterval(() => changeHex(), 1500);

You can check it by this URL here

about 4 years ago · Juan Pablo Isaza Relatório

0

You don't need JavaScript for this. This can be easily done by using CSS animation.

@keyframes bg {
  0% { background: #000000; }
  25% { background: #000099; }
  50% { background: #009999; }
  75% { background: #999999; }
  100% { background: #000000; }
}
body {
  background: #000;
  animation: bg 5s linear infinite;
}

Just change the colors to whatever you want. Working example: https://codepen.io/CodinCat/pen/bGaYRVz?editors=0100

If you need to start the animation dynamically by JavaScript, just put the animation part to a CSS class and toggle the class.


And just some additional notes. The reason that your code is not working is because your for loop is synchronous. The entire for loop ends immediately, maybe a few milliseconds. Browsers are smart enough to execute the JavaScript at once, and then re-paint the screen only once.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda