How to change the background color gradually based on the time of day using JavaScript?

- Andrés Cruz - ES En español

How to change the background color gradually based on the time of day using JavaScript?

View live demo

Changing the background color with JavaScript is quite common, but when you start doing it automatically and based on time, things get much more interesting. In one of my projects, I needed the page background to constantly change reflecting the current time, without buttons or user interaction. From there, this approach emerged, and in this article, I explain it to you step by step.

I am going to show you how to change the background color according to time in JavaScript, using hours, minutes, and seconds to generate dynamic hexadecimal colors in real time, without external libraries.

Introduction: dynamic backgrounds with JavaScript

When we talk about changing the background "over time," we don't mean clicking a button, but rather having the color:

  • Update automatically at a certain interval
  • Depend on a real temporal condition (hour, minute, or second)
  • Work without user intervention or page reload

The key is combining JavaScript's Date object with a recursive timer that refreshes the color every second.

How to change the background color with JavaScript

In JavaScript, changing the background color is quite straightforward. You just need to access the DOM and modify the background or backgroundColor property of the desired element.

Dynamically changing the body color

document.body.style.background = 'red';

This changes the background of the entire page immediately. It is the starting point for any dynamic background: a single line that gives you total control over the visual style of the body.

Changing the background color of a specific div

If you don't want to affect the entire page, you can target a specific element using getElementById and modify its backgroundColor property:

document.getElementById("contenedor").style.backgroundColor = "blue";

Getting the current time with JavaScript using Date()

Although CSS allows animations and transitions, JavaScript is the best option when the change depends on dynamic data like the current time. The Date() object gives us access to hours, minutes, and seconds in real time; from there we can build the color we need. In my case, I needed a background that evolved second by second without user intervention.

Generating a hexadecimal color from time

We will create a function called MostrarTiempoColor() whose content will be the following:

First we create a Date() object to get the current time, storing the hour, minutes, and seconds in their own variables:

d = new Date();
h = d.getHours();
m = d.getMinutes();
s = d.getSeconds();

Then we normalize the values. A valid hexadecimal color has exactly six digits, and the getHours(), getMinutes(), and getSeconds() methods return single-digit numbers when the value is less than 10. That is why we add a leading zero depending on the case, ensuring that the resulting hexadecimal always has the correct format:

if(h <= 9) h = '0'+h;
if(m <= 9) m = '0'+m;
if(s <= 9) s = '0'+s;

We generate the hexadecimal color by concatenating the # symbol with the hour, minutes, and seconds. The result is a string like #142305, which the browser interprets directly as a valid color:

color = "#"+h+m+s;

We change the background color of the entire document by assigning that value to the background property of the body:

document.body.style.background = color;

Finally, we display the hexadecimal code on screen using innerHTML on the element with id hexadecimal, so the user can see it in real time:

document.getElementById("hexadecimal").innerHTML = color;

Automatically changing the background color every second

Now it's time to make the background update constantly. For that, we define the full function and chain it recursively with a timer.

function MostrarTiempoColor() {
 const d = new Date();
 let h = d.getHours();
 let m = d.getMinutes();
 let s = d.getSeconds();
 if (h <= 9) h = '0' + h;
 if (m <= 9) m = '0' + m;
 if (s <= 9) s = '0' + s;
 const color = "#" + h + m + s;
 document.body.style.background = color;
 document.getElementById("hexadecimal").innerHTML = color;

Using setTimeout to update the color automatically

In my implementation I opted for setTimeout because it allows finer control over continuous execution. By placing it at the end of the function, the next call is not scheduled until the current iteration finishes, avoiding unexpected accumulations.

We invoke the already defined function every second by passing 1000 milliseconds as the second argument. This causes the background color to update once per second continuously:

setTimeout(MostrarTiempoColor, 1000);

Differences between setTimeout and setInterval for dynamic backgrounds

Both functions allow executing code repeatedly, but they don't behave the same way:

  • setInterval: executes the function every X milliseconds without waiting for the previous iteration to finish. In fast functions this is fine, but it can generate overlaps.
  • Recursive setTimeout: chains itself only when the function finishes, making it more stable and predictable in continuous processes.

For real-time dynamic backgrounds, I prefer setTimeout because it ensures calls do not accumulate if the browser is under load.

View live demo

Complete example: changing the background according to the current time

This is the complete and functional example. You can copy it directly into an .html file and open it in the browser to see how the background changes by itself, second by second:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Dynamic background with JavaScript</title>
</head>
<body onload="MostrarTiempoColor()">
 <h1>Current color:</h1>
 <div id="hexadecimal"></div>
 <script>
   function MostrarTiempoColor() {
     const d = new Date();
     let h = d.getHours();
     let m = d.getMinutes();
     let s = d.getSeconds();
     if (h <= 9) h = '0' + h;
     if (m <= 9) m = '0' + m;
     if (s <= 9) s = '0' + s;
     const color = "#" + h + m + s;
     document.body.style.background = color;
     document.getElementById("hexadecimal").innerHTML = color;
     setTimeout(MostrarTiempoColor, 1000);
   }
 </script>
</body>
</html>

Real-world use cases for dynamic backgrounds with JavaScript

This type of background is not just a visual experiment. I have used it in real projects for things like:

  • Visual clocks where the color is part of reading the time
  • Reactive backgrounds that reinforce an app's visual identity
  • Creative experiments and interactive portfolios
  • Automatic day / night mode based on the user's local time
  • Dynamic landing pages that generate a different first impression on each visit

Furthermore, by relying on the browser's local time, the behavior is completely predictable and consistent: you don't need servers, databases, or anything external.

Is this color change the same for all users?

Yes... as long as they are in the same time zone and access at the same second.

Remember that Date() uses the user device's local time, not the server's. This means that:

  • Two users in the same time zone logging in at the exact same second will see the exact same color
  • A user in another time zone will see the color corresponding to their local time

This approach is very similar to time-based synchronization solutions, with the advantage that it requires neither servers nor WebSockets: everything runs on the client.

Common errors when changing the background color with JavaScript

Some typical mistakes I've seen (and made) when starting with this type of effects:

  • Not normalizing single-digit values: if h is 9, the generated color would be #94500, which has only five characters and is not a valid hexadecimal.
  • Generating invalid hex colors: the browser simply ignores malformed values, leaving the background unchanged.
  • Using setInterval without control: if the function takes longer than expected or the browser queues tasks, duplicate calls can be created.
  • Updating styles unnecessarily: if the color doesn't change between two executions in the same second, reassignment of style.background generates a useless repaint.
  • Not testing across different browsers: although the Date API is standard, repaint and performance behaviors can vary slightly.

Avoiding these errors makes the difference between a quick demo and production-ready code.

Frequently asked questions about changing the background with JavaScript (FAQ)

  • Does changing the background every second consume many resources?
    • No. Modifying style.background is a very lightweight operation for the browser. It only involves a repaint, not a reflow, so the performance impact is minimal.
  • Is JavaScript or CSS better for automatically changing the background?
    • If the change depends on real time, JavaScript is the only viable option. CSS can only animate between predefined values, not react to external data at runtime.
  • Does it work in all modern browsers?
    • Yes. The Date API and the setTimeout and getElementById methods are supported in practically all browsers, including older ones.
  • Can I animate the transition between colors?
    • Yes. You just need to add a CSS transition on the background property: transition: background 1s ease;. The browser will smoothly interpolate between the old color and the new one.

Conclusion

Changing the background color according to time with JavaScript is a simple yet very powerful technique. From something as basic as the current time you can build dynamic, visual, and unique backgrounds, without external libraries and with very little code.

If you want to take it a step further, you can combine this approach with CSS gradients, transition animations, or even external data like weather forecasts. But as a foundation, this method is solid, clear, and easy to maintain. A good excuse to understand how JavaScript interacts with the DOM and system time.

Learn how to change the background color in real time using JavaScript, with Date(), setTimeout, and hexadecimal color values ​​based on the current time. No libraries required.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.