Click to return to the DHTML, HTML     
Changing Element Styles     Dynamic HTML    
Web Workshop  |  DHTML, HTML & CSS

Dynamic Styles


You can dynamically change the style of any HTML element in a document. You can change colors, fonts, spacing, indentation, position, and even the visibility of text. Because the Dynamic HTML Object Model makes every HTML element and attribute accessible, it is easy to use scripts to dynamically read and change styles. The following section describes dynamic styles and provides a general explanation of how to use the object model to examine and modify styles.

Making Styles Dynamic

Web authors gained unprecedented control over the look of documents with the introduction of cascading style sheets (CSS) in Microsoft® Internet Explorer 3.0. CSS allows authors and readers to attach a style to Web pages that defines the presentation of content by modifying style attributes of corresponding HTML elements.

Internet Explorer 4.0 takes CSS technology a step further, providing the ability to dynamically change any HTML attribute, at any time, on any element. Using simple JScript® (compatible with ECMA 262 language specification), or Visual Basic® Scripting Edition (VBScript), the attributes for any HTML element can be modified in response to any document or user event, and the page will automatically reflow without reloading the page from the server. This means that, for example, the STYLE element can be changed to change an element's inline CSS style, or any other HTML attribute (such as the SRC attribute on an IMG element).

Internet Explorer 5 and later versions allow Web authors to declare elements, properties, and formulas as CSS attributes and DHTML property values. Formulas for dynamic properties are set using the setExpression method and can be explicitly updated by invoking the recalc method. In addition, elements fire the onpropertychange event when object, expando, or style subobject properties change. For example, the width of a TABLE cell can be a formula that is automatically adjusted based on the measurements of adjacent objects. When using formulas for property and style values, the onpropertychange event and the new currentStyle object help authors monitor and respond to changes throughout a document.

Dynamic Styles Are Easy

You might expect that this new functionality would require that you learn a new set of HTML tags. However, dynamic styles have been designed to require no new HTML. CSS attributes can be set from the style subobject for each element, while regular HTML attributes are accessed as properties on each element. For instance, to change the color of text within an H1 heading when the user moves the mouse cursor over the heading, all you need to add is a simple piece of code known as an event handler.

<H1 onmouseover="this.style.color = 'red';">Make me red</H1>

The event handler, onmouseover="this.style.color = 'red';", takes a predefined action (onmouseover) and assigns an action for it to carry out when it fires (this.style.color = 'red'). It is just as easy to change not only the style but the content of a SRC attribute in the same manner.

<IMG src="before.gif" onmouseover="this.src = 'after.gif';">

In this example, as the mouse moves over the image, its source changes from "before.gif" to "after.gif".

As of Internet Explorer 5, authors can use the onpropertychange event to handle cases when styles and properties are modified. In the previous sample, moving the mouse cursor over the image changes the value of the SRC property. If other elements rely on the SRC of the image for aesthetics or positioning, the onpropertychange event is a convenient means to determine any additional actions.

For more information on using event handlers, see Understanding the Event Model.

Documents Are Dynamic

When the color of an element is changed dynamically, it still fits into the same physical space in the document as it did before the color change. This is a relatively simple task for the browser to carry out. However, there are other styles, such as fontSize or fontFamily, that, when changed, actually change the size of the element and the amount of space required to display that element in the document. Internet Explorer 4.0 and later versions handle such changes automatically by reflowing a document to ensure that all the elements fit perfectly without reloading the document from the server.

<html>
<body>
This is some text. 
<span style="color:blue" onclick="this.style.fontSize = '30'">

This is more text.</span>
This is even more text. 
</body>
</html>

This feature requires Internet Explorer 4.0 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

Initially, the document has three sentences, identical in font size and color. After clicking "This is more text," the text changes, increasing in size and changing to blue. The browser automatically adjusts the line spacing to accommodate the new text size.

Powerful Attributes

Because Internet Explorer 4.0 and later versions automatically reflow the document when attribute values change, some very powerful functionality can be built with very small amounts of code. For example, using the CSS display attribute, you can make elements on the page disappear and treat them as if they were never on the page in the first place.

<html>
<body>
<div style="cursor: hand" onclick="toggle(HideShow);">
Click Here</div>
<span style="color: blue" id=HideShow>This will go away</span><br>
This is some text
<script>
function toggle(e) {
  if (e.style.display == "none") {
     e.style.display = "";
  } else {
     e.style.display = "none";
  }
}
</script>
</body>
</html>

This feature requires Internet Explorer 4.0 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

This HTML displays three lines. When the user clicks the line that says "Click Here," the browser changes the display attribute of the SPAN element with the text "This will go away" to display: none, and the text beneath shifts up to occupy its space. When clicked again, the display attribute is reset so that the "Click Here" text is visible again.

Notice that by simply setting display: none on an element, it disappears and the browser automatically reclaims the space it occupied. This mechanism can be used to create pages that display new information, such as an expandable table of contents, as the user interacts with individual entries. The two supported values for the display property are none and "" (or null).

The sample above also makes use of the CSS cursor attribute. The cursor attribute allows a Web author to specify what the cursor will look like when it is over an element. In this case, the hand cursor was chosen to indicate that the text titled "Click Here" would perform an action when clicked, just like a text link on a Web page. Using the cursor attribute eliminates the need to use an anchor tag to change the cursor.

The set of valid values for the cursor attribute are crosshair, default, hand, move, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize, text, wait, and help.

While the display property makes an element invisible and allows the browser to reclaim the space that it occupied, the visibility property can be used to simply make an element disappear, but still reserve its space in the document.

The following example is identical to the previous demonstration, except it uses the visibility property instead of the display property.

<html>
<body>
<div style="cursor: hand" onclick="toggle(HideShow);">

Click Here</div>
<span style="color: blue" id=HideShow>This will go away</span><br>
This is some text
<script>
function toggle(e) {
  if (e.style.visibility == "hidden") {
     e.style.visibility = "visible";
  } else {
     e.style.visibility = "hidden";
  }
}
</script>
</body>
</html>

This feature requires Internet Explorer 4.0 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

Notice that in this example the line of text will become invisible, but the content below does not shift up to reclaim its space.

Special Considerations

You might have noticed that the names of many CSS properties contain a dash (such as background-color). The dash isn't a valid character for identifiers in most scripting languages. To get around this problem, continue to use the dashed name when specifying the CSS attribute in HTML or in a style sheet, but when accessing the attribute as a script property, remove the dash and capitalize the next letter. For example:

The CSS attributes that can be specified inline or in a style sheet are listed in CSS Attributes. The corresponding scriptable properties are listed as properties of the STYLE object.

Also notice that while any CSS property can be set at any time, the current settings on the STYLE element will only reflect its inline styles and not any inherited styles that are defined in a global style sheet with a STYLE or LINK tag. The following example shows what happens when a style is defined both globally and inline.

<html>
<head>
<style>
.class1 {font-family: arial}
</style>
</head>
<body>

<INPUT TYPE=button value="Check CSS" onclick="fnCheckCSS()">

<div id=SetByClass class=Class1>Set By Class</div>
<div style="font-family: arial">
      <div id=Inherited>Inherited</div>
</div>
<div id=DirectlySet style="font-family: arial">Directly Set</div>
<div id=SetWithScript>Set with Script</div>

<script>
function fnCheckCSS(){
      alert(SetByClass.style.fontFamily);
      alert(Inherited.style.fontFamily);
      alert(DirectlySet.style.fontFamily);
      SetWithScript.style.fontFamily = "arial";
      alert(SetWithScript.style.fontFamily);
}
</script>
</body>
</html>

This feature requires Internet Explorer 4.0 or later. Click the icon below to install the latest version. Then reload this page to view the sample.
Microsoft Internet Explorer

When this document loads, four alert dialog boxes pop up successively. The first two are blank, while the next two contain the text "arial." The fontFamily property returns "arial" only for the DIV that had the property set inline or in script. As of Internet Explorer 5, Web authors can use the currentStyle object instead of the style object to retrieve the value of the fontFamily property that is set in a STYLE object or is inherited.

Additional Topics

With Internet Explorer 4.0 and later, authors have total control over all attributes of all elements, at any time. Changes made to attributes that cause the page to change shape are handled automatically, with no additional script intervention by the author. Changing attributes through script can be done simply with inline script, or by pointing to a function where the element is accessed through a collection on the document. For more information about accessing elements through collections, see Scripting with Elements and Collections, or simply dive into the DHTML Reference for details on the document collections and on each HTML attribute that can be changed. You might also want to check out event handling for information on how to bind event handlers to one of the many events that the document can fire. The following articles contain additional information on dynamic styles.

Related Topics



Back to topBack to top

Did you find this topic useful? Suggestions for other topics? Write us!

© 1999 Microsoft Corporation. All rights reserved. Terms of use.