[ Team LiB ] Previous Section Next Section

12.6 Changing Page Background Colors and Images

NN 6, IE 4

12.6.1 Problem

You want to give users an opportunity to select a background color or background image for the current page or site.

12.6.2 Solution

Change one or more of the background-related style properties of the body element. The following examples demonstrate the range of options:

document.body.background = "url(watermark.jpg) repeat fixed";
document.body.backgroundAttachment = "fixed";
document.body.backgroundColor = "rgb(255, 255, 204)";
document.body.backgroundImage = "url(corp%20watermark.jpg)";
document.body.backgroundPosition = "5% 5%";
document.body.backgroundRepeat = "repeat-y";

12.6.3 Discussion

Several CSS style properties control aspects of element backgrounds. When applied to the body element, the background properties affect the entire page. Table 12-2 lists the scriptable properties and the types of values they accept.

Table 12-2. Background style properties and values.

Property

Description

background

Combination of several background styles in one specification, consisting of a space-delimited list of values for backgroundAttachment, backgroundColor, backgroundImage, backgroundPosition, and backgroundRepeat property values.

backgroundAttachment

How a background image clings to content during scrolling, controlled by constants fixed and scroll.

backgroundColor

Color specified as hexadecimal triplet (e.g., #ff00ff), CSS RGB value (e.g., rgb(255,0,255) or rgb(100%,0%,100%)), or color constant (e.g., green).

backgroundImage

URI of an external background image in CSS format (e.g., url(logo.jpg)).

backgroundPosition

Offset of a background image relative to the edges of the (body) element. Values are a space-delimited pair of length or percentage values (horizontal and vertical measures) or a pair of combinations of constants: bottom, center, left, right, or top. A single value can also be applied to both dimensions.

backgroundRepeat

Controls whether the image is to be repeated and whether the repeat is along a single axis, according to the constants: no-repeat, repeat, repeat-x, or repeat-y.

If you set both a background color and image, the image overlays the color and the background color shows through any transparent pixels in the image.

Providing users with a choice in background style (perhaps by way of a select element somewhere on the page) adds an extra burden if you want a user-friendly web site. You should preserve the setting so that the next time the user visits, the earlier choice applies to the current visit. While you can save this information in a database if you like, it is probably more convenient to preserve the setting in a client cookie. This obviates the need for a user to register and log into your site just to have a previously chosen skin applied to the site's look and feel.

Recipe 1.9 contains a generic cookie reading and writing library, which the following description assumes is loaded in the page (providing you with the setCookie( ) and getCookie( ) functions). In the following example, the user can select from a list of images located in a select element whose ID is bgChooser. The cookie preserves the URI of the most recently chosen image, and applies that to the body's background after the page loads (via an onload event handler in the <body> tag). The core of the routine is a function that reads the cookie and applies the value to the backgroundImage property. If the cookie is empty, the first item in the select list is used as a default:

// save user choice in cookie and set the style value
function savebgImage(evt) {
    evt = (evt) ? evt : ((event) ? event : null);
    if (evt) {
        var elem = (evt.target) ? evt.target : evt.srcElement;
        setCookie("bgImage", elem.value, getExpDate(180, 0, 0);
        // invoke function to change the visible image
        setbgImage( );
    }
}
   
// change bkgnd image after user selection or onload
function setbgImage( ) {
    var uri = getCookie("bgImage");
    // get reference to select element
    var selector = document.getElementById("bgChooser");
    if (uri) {
        // apply cookie value to background image
        document.body.style.backgroundImage = "url(" + uri + ")";
        // for onload, set select to the cookie value
        for (var i = 0; i < selector.options.length; i++) {
            if (uri =  = selector.options[i].value) {
                selector.options[i].selected = true;
                break;    
            }
        }
    } else {
        // if no cookie, set to whatever is selected by default
        document.body.style.backgroundImage = "url(" + selector.value + ")";
    }
}
   
...
<body onload="setbgImage( )">
...
<select id="bgChooser" onchange="savebgImage(event)">
    <option value="desk1.gif">Desk 1</option>
    <option value="desk2.gif">Desk 2</option>
    <option value="desk3.gif">Desk 3</option>
    <option value="desk4.gif">Desk 4</option>
</select>

Notice a subtle but important part of the setbgImage( ) function. The selected item in the select element should always echo the cookie value. A loop looks through all options of the select element to find a match between option and cookie values. When the loop locates a match, the option is made the selected item.

12.6.4 See Also

Recipe 12.4 for an alternative way of preserving and restoring style preferences by way of style sheets; Recipe 1.9 for a cookie library.

    [ Team LiB ] Previous Section Next Section