Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda