And now, I think the final tweak (I've tried to comment the code adequately, but if anyone has any questions about any particular part of it, feel free to ask):
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
/* set each td's default bg color in a stylesheet by id, or use a class or descendant selector if you want them all to default to the same bg color */
#td0 {background-color: orange;}
#td1 {background-color: brown;}
#td2 {background-color: black;}
#td3 {background-color: purple;}
</style>
</head>
<body>
<table id="thetable">
<tr>
<td id="td0"> </td><td id="td1"> </td><td id="td2"> </td><td id="td3"> </td>
</tr>
</table>
<script>
"use strict";
(function(){ // anonymous function wrapper keeps variable and function names out of the global scope
var timespans = [ // use as many timespans as you want, colors can repeat later with different times and/or td num, times should be sequential
{td: 1, bgc: "red", start: '0:00', end: '10:05'}, // {td: 0 index td num, bgc: "color", start: 'hour:minute', end: 'hour:minute'}
{td: 3, bgc: "blue", start: '10:06', end: '18:15'},
{td: 2, bgc: "#00ff00", start: '18:16', end: '23:01'},
{td: 0, bgc: "lightblue", start: '23:02', end: '23:59'}
], c = timespans.length, tsl = c, units = ['Hours', 'Minutes', 'Seconds'], // get timespans length, establish units for 'tomillis' conversion
the_tds = document.getElementById('thetable').getElementsByTagName('td'), curtd = {}; // reference the td's, establish var for current td (for later use)
while (--c > -1) {timespans[c].start += ':00'; timespans[c].end += ':59';} // add seconds to start and end times for more precise processing
function tomillis(cdtime){ // converts start and end colon delimited times to milliseconds since 1970/01/01
cdtime = cdtime.split(':');
var d = new Date(), t = -1;
while(++t < 3){ d['set' + units[t]](+cdtime[t]);}
return d.getTime();
}
function changetablebg(){
var curtime = new Date().getTime(), lim; // current milliseconds since 1970/01/01, var to later hold the current end time
while (++c < tsl) { // check timespan to find a match
if((lim = tomillis(timespans[c].end)) >= curtime && curtime >= tomillis(timespans[c].start)){
curtd.backgroundColor = ''; // revert previous td (if any) bg to it's default as set in style section
curtd = the_tds[timespans[c].td].style; // save refernece to current td
curtd.backgroundColor = timespans[c].bgc; // if found, set corresponding td's bg color to timespan's bgc
c = -1; // reset c for next run through
setTimeout(changetablebg, lim - curtime + 1500); // run again at one and a half seconds after lim (current end time)
break; // we've got a match, stop processing
}
}
}
changetablebg(); // initial run of the changetablebg function
})(); // end anonymous function wrapper
</script>
</body>
</html>
Bookmarks