George Zafiris George Zafiris - 3 months ago 7x
HTML Question

How to change CSS according time with JavaScript

Is there a way to change the background-color property, or any CSS property depending on a specific time (clock) of the day?

For example: For (9:00 - 12:00) the background color should be green, from 12:00 - 15:00 red and so on and so forth. I don't know if it's possible just with javascript or php. I've played around with some time intervals, but intervals reset each time I refresh the page.

Note: Say I open the page on 9:00 (I see a green background) and I close it. If I open it again on 11:00 the page should still be green.

Here's my HTML

<script src=""></script>
.timeDep {
background-color: #eee;
margin: 50px auto 0 auto;

<div class='timeDep'></div>

Any thoughts?

Thanks in advance!


Javascript would be a simple solution for this. Just need to get the current hour and set the background color based on the time.

var d = new Date();
var currHour = d.getHours();
if (currHour >= 9 && currHour <= 12) { = "green";
} else if (currHour > 12 && currHour < 17) { = "red";