Foxy Foxy -4 years ago 64
CSS Question

Change Which Table Row Background Color Changes Thoughout the Day Based on Time 0f Day

I have an HTML file that statically displays my school's schedule. How can I get table rows to change background color throughout the day based on time? I want the homeroom row to have a different background color only during homeroom and then return to normal when the row for first period has the different background color. And so on throughout the day.

<!DOCTYPE html>
<html>
<head>
<title>Schedule 1</title>
<style>
body {
background-color: black;
color:white;
text-align: center;
}
table, th, td {
color: black;
background-color: white;
text-align: center;
border: 2px solid black;
border-collapse: collapse;
font-size: 25px;
margin: auto;
padding: 5px;
}
th {
width: 300px;
height: 40px;
}
td:nth-child(1) {
width: 80px;
}
td:nth-child(2) {
width: 160px;
}
.table {
height: 500px;
}
</style>
</head>
<br><br>
<h1 style="color:white; bgcolor:black">SCHEDULE 1</h1>
<div class="table">
<table class="schedule">
<tr> <th width="300" colspan="2">REGULAR</th> </tr>
<tr> <td>HR</td><td>8:04 - 8:17</td> </tr>
<tr> <td>1</td><td>8:21 - 9:06</td> </tr>
<tr> <td>2</td><td>9:10 - 9:55</td> </tr>
<tr> <td>3</td><td>9:59 - 10:44</td> </tr>
<tr> <td>4</td><td>10:48 - 11:33</td> </tr>
<tr> <td>5</td><td>11:37 - 12:22</td> </tr>
<tr> <td>6</td><td>12:26 - 1:11</td> </tr>
<tr> <td>7</td><td>1:15 - 2:01</td> </tr>
<tr> <td>8</td><td>2:05 - 2:50</td> </tr>
</table>
</div>
</body>
</html>

Answer Source

You could do something similar to this, this uses jQuery. In your javascript, find out whether it is day or night (you could check for more times if you want) then depending on the result, update your dom styles. (This is in 24 hour format, you can change it to 12 hour format to make your if/else statements easier like this: ((hourCompare + 11) % 12 + 1)

var d = new Date();
var hourCompare = d.getHours();
if (hourCompare >= 8 && hourCompare <= 22) {
    //day time
    $('.tableCell').css("background-color", "yellow");
} else {
    //night time
    $('.tableCell').css("background-color", "blue");
}

I put together a jsfiddle for you. In order to get the correct colors, you will essentially have to write an if statement for each hour that you want to find and update the colors like I did in the fiddle. I wrote it to check for time updates every 3 seconds with setInterval. https://jsfiddle.net/zu588wjr/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download