JSFiddle - React, Tailwind, and code Playground
by secretgspot
HTML
<h1>Test</h1>
CSS
body {background: #ccc;}
.day {background: #f00;}
.night {background: #000;}
JavaScript
window.onload = function(){
var elem = document.body, //element with class
times = { //className : time range
'night' : '20:00:00 - 8:00:00',
'day' : '8:00:00 - 20:00:00'
},
timeout = 1000, //current time check interval
current = ''; //current class
function setCss( elem, name ){
if(name === current) return;
current = name;
var cls = elem.className.split(' '), i = cls.length;
while(i--)if( times[ cls[i] ] ) cls.splice(i, 1);
elem.className = cls.join(' ') + ' ' + name;
}
function getCss(){
var date = new Date(),
i, start, end, time;
for(i in times){
time = times[i].split(' - ');
if( time.length !== 2 ) continue;
start = date.setHours.apply( new Date(), time[0].split(':').concat(0) );
end = date.setHours.apply( new Date(), time[1].split(':').concat(0) );
if(end < start){
if(date <= end) return i;
end += 864e5;
}
if(date >= start && date <= end) return i;
}
return ''
}
(function setClass(){
setCss( elem, getCss() );
setTimeout( setClass , timeout)
}())
}