Changing background with JavaScript
Posted: Thu May 19, 2011 1:23 pm
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.
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.
<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.