I have a js script which checks the local time of the user and based on the local time switches image on the page.
The condition is that one image should be displayed from 6AM to 6PM and another one from 6PM until 6AM.
Everything works fine except that after midnight the condition doesn’t work properly and the selected image for that period is not displayed.
Here is the script I have:
function SetHiddenVariable() {
var localTime = new Date();
var hour = localTime.getHours();
var minute = localTime.getMinutes();
var time = hour + ':' + minute;
var suffix = "AM";
if(hour >=12)
{
suffix = "PM";
hour = hour - 12;
}
if(minute < 10)
{
minute = "0" + minute;
}
var timeMorning = new Date("1/1/2012 06:00 AM");
var timeEvening = new Date("1/1/2012 06:00 PM");
var realTime = new Date("1/1/2012 " + time);
var logo = document.getElementById('imgLogo');
if (realTime < timeMorning && realTime > timeEvening) {
if (logo == typeof ('undefined')) return;
logo.src = 'Images/night.png';
}
}
Any idea how can I solve this?
timevariable will not magically update when you change the value ofhourandminute. Place the assignment to thetimevariable after the if-conditions.document.getElementById,nullis returned. Your current check is flawed:typeof ('undefined')returnsstring, sologo == typeof ('undefined')will always be false. Replace it withlogo == null.Code: