Changing div background image based on time

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”;
}
}


You should use a css class instead of the “background” property.

You can try the “.style.backgroundImage” too.

See you :cool:

If I recall, this should do it:

document.getElementByID('id_of_the_div').style.backgroundImage="sunset.jpg";

That will select the element by its ID and set the background-image property.

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

this is what i tried to use
<script type=“text/javascript”>

var currentTime = new Date().getHours();
if ( currentTime> 6 | currentTime<9) {
if(document.body) {
document.body.background = “sunrise.jpg”;
}
}
else if (currentTime>=9 &&currentTime < 20) {
if(document.body) {
document.body.background = “daytime.jpg”;
}
}
else if (currentTime>20 &&currentTime < 24) {
if(document.body) {
document.body.background = “sunset.jpg”;
}
}
else {
if (document.body) {
document.body.background = “nighttime.jpg”;
}
}

</script>

As touched on by another poster, use CSS. Try this:


<style>
.bg1 {
background-image: url(images/bg1.gif); 
}
</style>


<body id="Body">


<script>
//time condition goes here
if (document.body){ 
document.getElementById('Body').className="bg1";
}
</script>

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:

document.body.style.backgroundImage=“url(”+currentImg+“)”;

[HIGHLIGHT=“”]
<!doctype HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=windows-1252”>
<title>Load Background Image</title>
<script type=“text/javascript”>
<!–
window.onload=function(){
var currentTime=new Date().getHours(), currentImg=“”;
//
if ( currentTime >=6 && currentTime <9){ currentImg=“sunrise.jpg”; }
else if ( currentTime >=9 && currentTime <18){ currentImg=“daytime.jpg”; }
else if ( currentTime >=18 && currentTime <19){ currentImg=“sunset.jpg”; }
else { currentImg=“nighttime.jpg”; }
//
document.body.style.backgroundImage=“url(”+currentImg+“)”;
}
// -----------
//–>
</script>
<style type=“text/css”>
<!–
body {
background-repeat: repeat;
background-color:#FFF;
margin:0px;
}
–>
</style>
</head>

<body>

</body>

</html>