DHTML supports dynamic objects and provides faster browsing through client-side processing.
Rick Dobson
Dynamic HTML (DHTML) is like HTML on steroids. It uses an object-based model that builds on HTML tags, yet it permits dynamic styles, content, and positioning as well as data binding to a browser. For the site visitor, DHTML Web pages deliver a richer, faster browsing experience through the magic of client-side processing.
This is the first in a three-part series on DHTML. A review of Cascading Style Sheets (CSS), a core DHTML enabling technology, leads into a discuss
ion of HTML tags as objects. This DHTML primer closes with an introduction to the event object and
bubbling
-- a new concept for scripting that simplifies and streamlines code.
Not surprisingly, Netscape and Microsoft offer different DHTML implementations. Both companies promise that these versions will converge after the World Wide Web Consortium (W3C) issues final recommendations. This article uses Microsoft's version because it offers more capabilities (for more information, see "Dynamic HTML Comparisons," September BYTE, page 23). It offers more than 90 HTML elements with properties, methods, and events. For detailed documentation, visit
http://www.microsoft.com/msdn/sdk/inetsdk/help/
. The site also includes many code samples that can jump-
start you on your way to learning this new technology.
Tags and Scripting Objects
DHTML relies on CSS. This technology appeared initially with Microsoft Internet Explorer 3 and is approved by the W3C. CSS allows developers unprecedented control over the appearance and positioning of content on Web pages. It generally helps Web content authors separate style from content. (Look, Ma, positioning without resorting to tables!)
CSS offers four ways for site builders to incorporate style components into a document. First, you can reference an external style sheet. Second, you can physically import an external style sheet. Third, your code can create and modify style rules with a pair of style tags located inside the current document. Fourth, you can place in-line style attributes within the tags on a document. There are over 60 style attributes for fine-tuning the appearance of your Web pages.
All the traditional HTML tags become DHTML objects. DHTML developers must write short VBScript o
r JavaScript programs that enable end-user interactivity by manipulating object methods and properties. A rich array of events offers a broad selection of options for triggering code that responds to user and Web actions.
Each DHTML tag has a corresponding scripting element. The P tag, for example, matches a P element (or scripting object). The P tag's read-only
parentElement
property returns the next object up the document hierarchy -- the
Body
element, which is owned by the HTML BODY tag. The P tag's read/write
innerText
property lets developers dynamically read and replace the text within a P scripting object.
Two P methods specifically support dynamic content operations. First, the
InsertAdjacentHTML
method lets you insert new HTML into a P tag. Second, the
InsertAdjacentText
method helps to update a paragraph's content, but not its HTML code.
Dynamic Styles
Many developers will be attracted to DHTML by its ability to change style in
response to user and system events. One easy way to achieve this is with the
className
property. This property applies to block elements, such as P, and it corresponds to the CLASS attribute. To change styles, simply set the
className
property to a new style rule.
To revise a property, your code must first reference the underlying object. The
all
collection often makes this easy. Use the
all
collection's tag property to flag all similar elements in a document. Then, use the tag's
item
method to reference specific instances of an element in a document. Then, you set the instance's
className
property equal to the new style rule.
The Classy Style Change listing in
"Code Gallery"
illustrates these principles. The HTML document contains two style rules and two paragraph blocks. The block containing Welcome! has its CLASS attribute set to the
littlegreen
style rule. The other paragraph uses the default style. Clicking a
nywhere in the document fires the
Body
's
onclick
event. This event launches the JavaScript
changeStyle
function. It uses the index numbers of 0 and 1 to reference the document's first and second paragraphs. The JavaScript sets the
className
properties of the first and second paragraphs to the
bigred
and
littlegreen
style rules, respectively.
The Stylistic Style Change code segment in
"Code Gallery"
illustrates a more granular technique for achieving the same result. This version of
changeStyle
sets specific properties of the
style
object for paragraph blocks. When you need finer-grained control than the
className
property permits, or when you want to make ad hoc changes, consider using style object properties.
Events and Bubbling
DHTML introduces a new
event
object that tracks the firing of events. Its properties permit identifying the element where the event occurred, the curre
nt state of the keyboard keys, the location of the mouse, and the state of the mouse buttons. For example, the
onclick
and
onmouseover
events capture end-user mouse behavior relative to HTML tags, and the
Body
's
onload
event fires immediately after the browser loads a document. You write the handlers that respond to these events. Event handlers can be written in European Computer Manufacturers Association (ECMA) JavaScript or Microsoft VBScript.
DHTML events can bubble up from lower to higher document hierarchy levels. This permits events for lower-level objects to bubble up and trigger event handlers for unrelated upper-level objects. Because of this potential, you must consider whether your code should explicitly turn off bubbling.
The
"Bubbling Up"
code segment illustrates how to use the event object, and it reinforces basic scripting techniques. The document in this code segment includes a couple of H1 blocks and a P block. Within the P
block is a B block. The P block has an event handler,
setParaStyle
, that captures the
onclick
event.
Clicking anywhere in the P block launches its
onclick
event handler. It starts by setting a variable,
el
, equal to the source element for the event. This will be either P or its embedded B block. If the tag's name is not P, then the code sets
el
equal to the tag's parent, thereby forcing
el
to P. Notice that the function uses the
tagName
property of the
srcElement
property of the event object to detect where in the paragraph a user clicked. The code uses the
textDecoration
property of
el
's style object to underline the whole paragraph, no matter where the user clicks on the line.
The final line in
setParaStyle
turns off event bubbling if the user clicks in the B block. This line selectively controls event bubbling, depending on where in the line a user clicks. Clicks anywhere on the line -- except in
the B block -- permit the event object to bubble up the document hierarchy to the Body level and beyond.
Body
's event handler,
setBodyStyle
, then changes the color of the document's two H1 blocks.
The
setBodyStyle
function also demonstrates some interesting scripting techniques. First, it uses the
innerText
property of the
srcElement
object to echo back which document object caused the function to run. Second, it uses a
for
loop to iterate through the item indices for the H1 tag objects.
Hard Choices
DHTML offers Web developers the potential of improved speed and interactivity; it offers Web users a richer browsing experience. The technical challenge of moving to DHTML calls out to HTML and Visual Basic developers because it builds directly on HTML but offers an object-oriented model that is familiar to VB programmers.
The operational challenge of moving to DHTML might be more problematic. Will folks be able to view the effects?
The answer is "Yes" only if they have the Internet Explorer 4 browser. There are two solutions to this predicament. First, target DHTML for environments where you can mandate the browser (an intranet or extranet). Second, make your Net applications so compelling that folks voluntarily upgrade to the free Microsoft Internet Explorer browser.
A Classy Style Change
<HTML><HEAD><STYLE>
.bigred {font-size:24pt;
color:red}
.littlegreen {font-size:10pt;
color:green}
</STYLE><SCRIPT LANGUAGE="JavaScript">
function changeStyle() {
document.all.tags("P").item(0)
.className = "bigred";
document.all.tags("P").item(1)
.className = "littlegreen";}
</SCRIPT><BODY onclick="changeStyle()">
<P CLASS="littlegreen">Welcome!
<P>Click anywhere to accentuate Welcome!
</BODY></HTML>
A Stylistic Style Change
function changeStyle() {
d
ocument.all.tags("P").item(0).
style.fontSize = "24pt";
document.all.tags("P").item(0).
style.color = "red";
document.all.tags("P").item(1).
style.fontSize = "10pt";
document.all.tags("P").item(1).
style.color = "green";}
<HTML><HEAD><SCRIPT LANGUAGE="JavaScript">
function setParaStyle() {
var el = window.event.srcElement;
while (el.tagName != "P")
{el = el.parentElement;}
el.style.textDecoration = "underline";
if (event.srcElement.tagName == "B")
event.cancelBubble = true;}
function setBodyStyle() {
alert ("Clicked heading is: "
+ event.srcElement.innerText)
var coll = document.all.tags("H1");
for (i=0; i<coll.length; i++)
coll.item(i).style.color = "green";}
</SCRIPT></HEAD>
<BODY onclick="setBodyStyle()">
<H1>First Welcome!</H1>
<H1>Second Welcome!</H1>
<P onclick="setParaStyle()">Click anywhere,
<B>bu
t here</B>, to bubble up.
</BODY></HTML>
Rick Dobson, Ph.D., is president of CAB, Inc., a database and Internet development consultancy. You can reach him by sending e-mail to
Rick_Dobson@msn.com
.