How to change the color progressively according to the time with JavaScript?

- Andrés Cruz

En español

How to change the color progressively according to the time with JavaScript?

Demo

In this post we will see how to change the color of some element of a web page according to the time of day (in this case we will change the background color of the body) with a simple JavaScript.

Creating the function to change color based on time of day (JavaScript)

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

First we create an object of type Date() to obtain the current time (hour, minutes and second):

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

This section of JavaScript code allows you to convert a number (hour, minute and/or second) from a single digit to two; adding a zero in front as appropriate; in this way to be able to form a hexadecimal composed of six digits regardless of the time; As we can see, the numbers to be treated correspond to the current time (the hour, minute and second):

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

We generate the color by combining the hour, minutes and seconds:

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

We change the background color of some element; in our example, the color of the HTML document itself:

document.body.style.background = color;

We insert the hexadecimal color code generated above:

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

We invoke the already defined function every second with the method provided by JavaScript called setTimeout; which means we update the background color every second:

setTimeout(MostrarTiempoColor, 1000);

Link of Interest

Final score

 

Demo

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 1d 08:21!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!