Archives
 
 
 
  Special
 
 
 
  About Us
 
 
 

Newsletter
Free E-mail Newsletter from BYTE.com

 
    
           
Visit the home page Browse the four-year online archive Download platform-neutral CPU/FPU benchmarks Find information for advertisers, authors, vendors, subscribers Request free information on products written about or advertised in BYTE Submit a press release, or scan recent announcements Talk with BYTE's staff and readers about products and technologies

ArticlesDynamic HTML Explained, Part 1


November 1997 / Core Technologies / Dynamic HTML Explained, Part 1

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.


Code Gallery


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";}




Bubbling Up

<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 .

Up to the Core Technologies section contentsGo to previous article: SearchSend a comment on this articleSubscribe to BYTE or BYTE on CD-ROM  
Flexible C++
Matthew Wilson
My approach to software engineering is far more pragmatic than it is theoretical--and no language better exemplifies this than C++.

more...

BYTE Digest

BYTE Digest editors every month analyze and evaluate the best articles from Information Week, EE Times, Dr. Dobb's Journal, Network Computing, Sys Admin, and dozens of other CMP publications—bringing you critical news and information about wireless communication, computer security, software development, embedded systems, and more!

Find out more

BYTE.com Store

BYTE CD-ROM
NOW, on one CD-ROM, you can instantly access more than 8 years of BYTE.
 
The Best of BYTE Volume 1: Programming Languages
The Best of BYTE
Volume 1: Programming Languages
In this issue of Best of BYTE, we bring together some of the leading programming language designers and implementors...

Copyright © 2005 CMP Media LLC, Privacy Policy, Your California Privacy rights, Terms of Service
Site comments: webmaster@byte.com
SDMG Web Sites: BYTE.com, C/C++ Users Journal, Dr. Dobb's Journal, MSDN Magazine, New Architect, SD Expo, SD Magazine, Sys Admin, The Perl Journal, UnixReview.com, Windows Developer Network