This code should display the time, in red if it is after 8:00 at night in the Central time zone, and in green if it is after 7:30 a.m. Unfortunately, this is my first time with Javascript and I’m apparently making some mistake. Nothing is displayed. Can anyone help me find the problem?
<script type="text/javascript">
var centralDate = getOffsetDate(360);
function getOffsetDate(offsetInMintues) {
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - offsetInMintues);
return d;
}
function GetClock(){
d = getOffsetDate();
nhour = d.getHours();
nmin = d.getMinutes();
if(nhour == 0) {ap = " AM";nhour = 12;}
else if(nhour <= 11) {ap = " AM";}
else if(nhour == 12) {ap = " PM";}
else if(nhour >= 13) {ap = " PM";nhour -= 12;}
if(nmin <= 9) {nmin = "0" +nmin;}
var h = centralDate.getHours();
var m = centralDate.getMinutes();
if (h >= 20 ||
h <7 ||
(h == 7 && m <= 30)) {
c="#FF0000"
}
else {c=#00FF00"}
document.getElementById('clockbox').innerHTML=""+nhour+":"+nmin+ap+"";
setTimeout("GetClock()", 1000);
}
<FONT COLOR=c>;
window.onload=GetClock;
</FONT>
</script>
<div id="clockbox"></div>
You’re not passing anything into
getOffsetDate()insideGetClock, which hoses up all the numeric calculations.(Plus the stuff I mentioned in my comments.)
See the fiddle
(The
setTimeoutis commented out for my sanity.)You don’t actually change the color anywhere, either; you just set a value, then never do anything else again.
Plus you have HTML inside your
<script>tags, which doesn’t work. Rather change the<font>tag attribute… although nobody actually uses font tags anymore now that we know CSS, so you’ll probably want to do that instead for your own sake.(I’m not actually sure you want to call
getOffsetDate()fromGetClock, but it’s not clear to me what you’re trying to do, so I don’t know. In the fiddle I left it as-is and pass in a 0-minute offset.)