I want to change the background of my main div depending on the time of day. Right now this code works for two time of day, day and night but it only works on the “body” tag not on a div. How would i modify it to change a div background rather then the “body” background
var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 20) {
if (document.body) {
document.body.background = “sunrise.jpg”;
}
}
else {
if (document.body) {
document.body.background = “sunset.jpg”;
}
}
thanks for your quick replies, i assume i would have to completely change it if i wanted to change it to more then two options, ie 0-8,8-16 and 16-24 or more even
The following script loads the background images based on time of day. You need to run it after the page loads, so that there is a document.body available. I have done this using window.onload. Notice the syntax for the background image, which is different to your own effort: