Dynamic HTML: The Definitive Reference, 2rd Ed.Dynamic HTML: The Definitive ReferenceSearch this book

5.6. Changing Applied Style Values

With so much of the rendering detail for an element in the hands of style sheets, you will likely modify style values to control a variety of DHTML effects. We saw some examples of this in the positioning scripts of Chapter 4. Additional style properties await your magic touch. The IE and W3C DOMs provide several ways to adjust the value of style attributes being applied to an element at any given moment. The two most popular are modifications via an element's style and className properties; other approaches dive more deeply into the style sheets and their components.

5.6.1. The style Property

Perhaps the simplest way to adjust a single style attribute is through an element's style property. An element's style property is, itself, an object whose properties consist of all possible style attributes supported by the browser's DOM.

Before going further, it is helpful to acknowledge the similarities and differences between the style objects implemented in IE for Windows and the W3C DOM (as implemented in Netscape 6 and IE 5/Mac). Typically, browsers that implement proprietary style attributes that extend the list provided by the CSS standard also expose those proprietary style attributes as scriptable properties. For example, while CSS2 does not include an attribute to specify the opacity of a text element, IE and the Mozilla engine in Netscape 6 implement their own extensions for this feature (the IE opacity filter attribute and the Mozilla mozOpacity attribute). If you implement scripted styles across DOMs, be sure the styles and values you use are supported by both DOMs (as detailed in Chapter 11) or provide suitable workarounds.

Deeper down, however, the IE and W3C style objects have different structures. In the W3C DOM's formal structure, what you think of as a style object is known as a CSSStyleDeclaration object (terminology that scripts don't work with directly). This object features a variety of methods for reading and writing style attribute values that are very much in keeping with the rest of the formal DOM. For example, setting the color style attribute of an element looks like the following:

document.getElementById("myP").style.setAttribute("color", "rgb(255, 0, 0)", "");

Fortunately, the DOM standard also offers a convenient collection of properties that lets scripts access properties just as IE has been doing it all along. (This collection is of DOM type CSS2Properties, which is not a requirement for DOM compliance, but is supported in Netscape 6 and IE 5/Mac just the same.) This collection leads to the more common style adjustment syntax as in the following:

document.getElementById("myP").style.color = "rgb(255, 0, 0)";

The point of discussing these inner workings has to do with the data types of values assigned to style object properties. The implementation of the CSS2Properties collection supports string values exclusively, even if the values consist only of numbers. This makes sense in most cases, because even length values have numeric values followed by unit types, such as "14px".

But also be aware that several IE-only style object attributes require either numeric or Boolean values. For example, the style.posLeft property consists of only the numeric portion of the string-based style.left property.

With that business out of the way, we'll now examine one way of cycling a chunk of text through a sequence of colors. Example 5-9 shows a version using W3C DOM referencing syntax. A single span element in the body has the color property of its style changed in a function that is invoked often enough (via setInterval( )) to run through the cycle seven times, and then stop (to prevent user nausea). For programming convenience, the color names are stored in a global variable array, with other global variables maintaining a record of the color currently showing and the elapsed number of color changes. No positioning or other tactics are required.

Example 5-9. Inline text color change via the style property

<html>    
<head>
<title>Changing style Properties</title>
<style type="text/css">
    #hot1 {color:red}
</style>
<script language="JavaScript" type="text/javascript">
// Set global variables
var totalCycles = 0;
var currColor = 0;
var colors, intervalID;
// Build array of color names
function init( ) {
    colors = ["red", "green", "yellow", "blue"];
}
// Advance the color by one
function cycleColors( ) {
    // reset counter to 0 if it reaches 3; otherwise increment by 1
    currColor = (currColor == 3) ? 0 : ++currColor;
    // set style color to new color from array
    document.getElementById("hot1").style.color = colors[currColor];
    // invoke this function again until total = 27 so it ends on red
    if (totalCycles++ < 27) {
        intervalID = setTimeout("cycleColors( )", 100);
    } else {
        clearTimeout(intervalID);
    }
}
</script>
</head>
<body onload="init(); cycleColors( );">
<h1>Welcome to the <span id="hot1">Hot Zone</span> Web Site</h1>
<hr>
</body>
</html>

Any valid color string value could work in this code. Chapter 11 explains color value formats for style attributes.

5.6.2. The className Property

Another popular way to modify styles applied to an element is to predefine rules for more than one class selector, and then use scripts to switch the selector assigned to an element's className property. This approach is particularly convenient if the changes you wish to make affect multiple attributes.

Example 5-10 builds upon Example 5-9 by defining four style rules, each with a different class selector. The array for this version contains not color values, but class names. The repeated call to cycleColors( ) then simply assigns the next name in sequence to the span element's className property. Each change of the className property changes both the color and border style properties of the span element.

Example 5-10. Inline style change via the className property

<html>    
<head>
<title>Changing className Properties</title>
<style type="text/css">
    .red    {
              color: red;
              border: 2px solid red;
            }
  
    .green  {
              color: green;
              border: 2px solid yellow;
            }
  
    .yellow {
              color: yellow;
              border: 2px solid blue;
            }
  
    .blue   {
              color: blue;
              border: 2px solid green;
             }
</style>
<script language="JavaScript" type="text/javascript">
// Set global variables
var totalCycles = 0;
var currColor = 0;
var classes, intervalID;
// Build array of rule selector names
function init( ) {
    classes = ["red", "green", "yellow", "blue"];
}
// Advance the color by one
function cycleColors( ) {
    // reset counter to 0 if it reaches 3; otherwise increment by 1
    currColor = (currColor == 3) ? 0 : ++currColor;
    // set style color to new color from array
    document.getElementById("hot1").className = classes[currColor];
    // invoke this function again until total = 27 so it ends on red
    if (totalCycles++ < 27) {
        intervalID = setTimeout("cycleColors( )", 100);
    } else {
        clearTimeout(intervalID);
    }
}
</script>
</head>
<body onload="init(); cycleColors( );">
<h1>Welcome to the <span class="red" id="hot1">Hot Zone</span> Web Site</h1>
<hr>
</body>
</html>

5.6.3. Other Techniques

That the IE and W3C DOMs expose not just style elements as objects, but also their content as styleSheet objects, might lead some scripters to get perhaps too creative in modifying applied styles. Each <style> or <link rel="stylesheet"> tag in a document creates a styleSheet object that is accessible through the document.styleSheets array. If you specify just one <style> tag in the document, document.styleSheets[0] returns a reference to that styleSheet object.

From that reference, a script can inspect and modify the contents of the style sheet, albeit via occasionally different syntax for IE and W3C DOMs (IE 5/Mac observes both syntaxes). Table 5-1 lists the most important styleSheet object properties implemented in the two DOMs.

Table 5-1. Key properties of the styleSheet object

W3C property

Description

IE property

cssRules

Array of rules within the style sheet

rules

n/a

Complete text of all rules

cssText
disabled

Boolean to enable/disable entire style sheet

disabled
href

URL for <link>

href
ownerNode

Reference to style or link element

owningElement

Each styleSheet object has a property that returns an array of rules that belongs to the style sheet. The IE DOM calls these objects rule objects; the W3C calls them cssRule objects. You can reference a rule via its numeric index within the array. For example, here's a reference to the third rule in a page's only style sheet via the W3C DOM:

var oneRule = document.styleSheets[0].cssRules[2];

In IE syntax (required for IE/Windows), the expression is:

var oneRule = document.styleSheets[0].rules[2];

Properties of an individual rule object (regardless of how you reference the object) are a bit thin, and only partially helpful across DOMs. Both models support the selectorText property, which returns a string of the selector for the rule (although IE returns tag type selectors in uppercase, regardless of the source code case). Only the W3C cssRule object provides a direct cssText property to get the actual text. But both DOMs provide a style property, which returns a style (or W3C CSSStyleDeclaration) object whose properties reveal the individual style attribute settings for the rule. The following function demonstrates the cross-DOM syntax that sets the font-size attribute of a p-selectored rule in a style sheet:

function setSize(n) {
    var sheets = document.styleSheets[0];
    var ruleList = (typeof sheets.cssRules != "undefined") ? sheets.cssRules : 
    ((typeof sheets.rules != "undefined") ? sheets.rules : null);
    if (ruleList) {
        for (var i = 0; i < ruleList.length; i++) {
            if (ruleList[i].selectorText.toLowerCase( ) == "p") {
                ruleList[i].style.fontSize = n + "pt";
                break;    
            }
        }
    }
}

Additional facilities for modifying styleSheet objects include methods for adding and deleting individual rules within the styleSheet object (with incompatible syntax for IE and W3C DOMs). You can learn the details in Chapter 9.

Despite the substantial flexibility available through the styleSheet object, you will experience better reliability and compatibility (especially with Opera) if you perform your style changes via the style or className properties of the element you wish to modify. Working with styleSheet objects is best left to those times when scripts are creating new style sheets or rules on the fly.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.