Unobtrusive Seasonal Background
To examine how this works let's look at a script that puts a different background image behind part of the content of the page depending on which season it is.
The code that we need for this example is in three separate parts. The first of these is the HTML which defines the content of our web page. For the purpose of this example we just have several short paragraphs on the page some of which will have a background added and some that will not.
Copy and save the above content as season.htm.
There are three lines in this code that allow our script to work.
- The stylesheet that defines our page appearance is called season.css and is linked into the HTML using a link tag.
Copy and save the above content as season.css.
Copy and save the above content as season.js.
The start function contains the code will be run to add the background image to the div.The backImg array references the four different background images, one of which will be added as a background by the rest of the code. We use the getElementById call to reference the div and to add the selected background to it.
We need to ensure that the div has actually loaded into the page before trying to attach the background (otherwise we will get an error). To ensure that the background is added as quickly as possible we set up a loop to test for when it exists rather than waiting until the page finishes loading.
The only thing that you need to add to the above code to get your unobtrusive seasonal background script to work is to save the four images that you want it to use to the same folder as the above three files.