George Zafiris George Zafiris - 4 months ago 9
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

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style>
.timeDep {
width:200px;
height:200px;
background-color: #eee;
margin: 50px auto 0 auto;
}
</style>
</head>
<body>
<script>
$(function(){
//Code
});
</script>

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


Any thoughts?

Thanks in advance!

Answer

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) {
    document.body.style.backgroundColor = "green";
} else if (currHour > 12 && currHour < 17) {
    document.body.style.backgroundColor = "red";
}
Comments