Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!