Page 1 of 1

Changing background with JavaScript

Posted: Thu May 19, 2011 1:23 pm
by pasqo83
I found some useful javascript coding from another site that might be of interest to some people. It changes the background according to the time of day it is.
<html>
<head>

<style type = "text/css">
body {background-color:#FFFFFF;} 
</style>
</head>

<body onload = "chgbg()">

<script type="text/javascript">

function chgbg() {
var d = new Date();
var h = d.getHours();

if ((h >= 6) && (h < 9)) {document.body.style.backgroundColor = "#FFFFFF"; document.body.style.backgroundImage="url(sunrise.jpg)"}
if ((h >= 9) && (h < 20)) {document.body.style.backgroundColor = "#FFFFFF"; document.body.style.backgroundImage="url(day.jpg)"}
if ((h >= 20) && (h < 22)) {document.body.style.backgroundColor = "#FFFFFF"; document.body.style.backgroundImage="url(sunset.jpg)"}
if ((h >= 22) || (h<6)) {document.body.style.backgroundColor = "#FFFFFF"; document.body.style.backgroundImage="url(night.jpg)"}

window.setTimeout (chgbg, 5000);  // update time (hour) every five seconds
}
</script> 

</body>
</html>

The background image is changed with css, not document.write() which over-writes the current content of the page. If JavaScript is disabled (but how many people in fact do have it disabled?) then the default background colour (white) is shown.

:)

Re: Changing background with JavaScript

Posted: Thu May 19, 2011 1:52 pm
by nyo
Thanks pasqo, I could use that.

Re: Changing background with JavaScript

Posted: Thu May 19, 2011 1:52 pm
by jacek
every 5 seconds seems excessive if it will only update every few hours ;)

Re: Changing background with JavaScript

Posted: Thu May 19, 2011 11:11 pm
by Dylan
jacek wrote:every 5 seconds seems excessive if it will only update every few hours ;)
:lol:
Either way, handy piece of code I suppose depending on the site. As for people disabling JavaScript, I do not know anyone who does it on a personal computer; I know my school has it disabled by default so I'm not sure.

Re: Changing background with JavaScript

Posted: Thu May 19, 2011 11:55 pm
by jacek
It's not like this is critical to the site, so it's still fine ;)