Home > Back-end >  how to change background color to multiple colors as an animation using Javascript
how to change background color to multiple colors as an animation using Javascript

Time:04-03

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>

CodePudding user response:

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

CodePudding user response:

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.

  • Related