Changing background with JavaScript

Written something you are proud of, post it here.
Post Reply
User avatar
pasqo83
Posts: 106
Joined: Sat May 14, 2011 6:23 am

Changing background with JavaScript

Post 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.

:)
  • Empty your mind, be formless like water. If you put water into a cup, it becomes the cup. You put water into a bottle and it becomes the bottle. You put it in a teapot it becomes the teapot. Now, water can flow or it can crash. Be water my friend.
nyo
Posts: 124
Joined: Mon May 09, 2011 1:55 pm
Location: Mobile

Re: Changing background with JavaScript

Post by nyo »

Thanks pasqo, I could use that.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Changing background with JavaScript

Post by jacek »

every 5 seconds seems excessive if it will only update every few hours ;)
Image
User avatar
Dylan
Posts: 150
Joined: Fri May 06, 2011 7:14 pm

Re: Changing background with JavaScript

Post 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.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Changing background with JavaScript

Post by jacek »

It's not like this is critical to the site, so it's still fine ;)
Image
Post Reply