Export (0) Print
Expand All

About the DHTML Object Model

Note  As of December 2011, this topic has been archived and is no longer actively maintained. For more information, see Archived Content. For information, recommendations, and guidance regarding the current version of Windows Internet Explorer, see Internet Explorer Developer Center.

The Dynamic HTML (DHTML) Document Object Model (DOM) allows authors direct, programmable access to the individual components of their Web documents, from individual elements to containers. This access, combined with the event model, allows the browser to react to user input, execute scripts on the fly, and display the new content without downloading additional documents from a server. The DHTML DOM puts sophisticated interactivity within easy reach of the average HTML author.

What Is the Object Model?

The object model is the mechanism that makes DHTML programmable. It doesn't require that authors learn new HTML tags, and it doesn't involve any new authoring technologies. In fact, the object model builds on functionality that authors have used to create content for previous browsers. Remember setting the value for a form element in script, or adding onmouseover events to links in Microsoft Internet Explorer 3.0? If so, you've been using a limited form of the object model to access your HTML with script.

What's different in the current object model is that now every HTML element is programmable. This means every HTML element on the page can have script behind it that can be used to interact with user actions and change the page content dynamically. This event model lets a document react when the user has done something on the page, such as moving the mouse pointer over a particular element, pressing a key, or entering information into a form input. Each event can be linked to a script that tells the browser to modify the content on the fly, without having to go back to the server for a new file. The advantages to this are that authors will be able to create interactive Web sites with fewer pages, and users do not have to wait for new pages to download from Web servers, increasing the speed of their browsing and the performance of the Internet as a whole.

Accessing Elements with Script

Every HTML element is a scriptable object in the object model, with its own set of properties, methods, and events. However, to write script for each element object, the author must know how to get to an element.

The object model focuses on collections of elements, a hierarchy of groupings that the elements fall into. The most important of these collections are the all collection and the children collection. A DHTML document is a structured arrangement of elements, and in the following example, each element has a scope of influence that depends on where in the document the tags appear.



<HTML>
    <BODY>
        <DIV>
            <P>Some text in a 
                <B>paragraph</B>
            </P>
            <IMG id=image1 src="mygif.gif">
        </DIV>
        <IMG id=image2 src="mygif.gif">
    </BODY>
</HTML>


In the preceding example, the div object contains (and is the parent of) the p object and the img object called image1. Conversely, image1 and the p are children of the div. The img object called image2, however, is a child of the body object.

Each element object has an all collection that contains all the elements that are beneath that element in the hierarchy, and a children collection that contains only the elements that are direct descendants of that element. In the preceding example, the b would be in the div object's all collection, but would not appear in the div object's children collection. Similarly, the div is a member of the body object's children collection, but the p is not.

In addition to these collections for each element, the document itself (represented by the document object) has a number of element and nonelement collections. The most important collection is an all collection that contains all the elements on the Web page. This collection is the primary way to access elements through script. For more information about using collections, see Scripting with Elements and Collections.

Events: Bubbling, Canceling, and Handling

Clicking a button, moving the mouse pointer over part of the Web page, selecting some text on the page—these actions all fire events, and a DHTML author can write code to run in response to the event. This particular piece of code is generally known as an event handler, because that's what it does, it handles events.

Event handling is not unique to Microsoft Internet Explorer 4.0 or even Internet Explorer 3.0; Netscape Navigator 3.x and Communicator also handle events. However, in Internet Explorer 4.0, the HTML elements on a Web page that are the source of the events, and the types of events that are generated, have been greatly expanded. Previously, only a small set of HTML elements could generate events, such as anchors, image maps, form elements, applications, and objects. With the Internet Explorer 4.0 event model, every HTML element on the page can be the source for a full set of mouse and keyboard events.

The following is a set of common events that every HTML element generates in Internet Explorer 4.0.

Mouse eventGenerated when the user:
onmouseover Moves the mouse pointer over (that is, enters) an element.
onmouseout Moves the mouse pointer off (that is, exits) an element.
onmousedown Presses any of the mouse buttons.
onmouseup Releases any of the mouse buttons.
onmousemove Moves the mouse pointer within an element.
onclick Clicks the left mouse button on an element.
ondblclick Double-clicks the left mouse button on an element.
Keyboard eventGenerated when the user:
onkeypress Presses and releases a key (full down-and-up cycle). However, if a key is held down, multiple onkeypress events are fired.
onkeydown Presses a key. Only a single event is fired, even if the key is held down.
onkeyup Releases a key.

 

To help authors build code that is compact, simpler, and easier to maintain, Internet Explorer 4.0 introduces event bubbling as a new way to handle events. Windows, OS/2, OSF Motif, and almost every other graphical user interface (GUI) platform uses this technique to process events in their user interfaces. However, event bubbling is new to HTML and provides an efficient model for incorporating event handling into Web documents.

Previously, if an HTML element generated an event, but no event handler was registered for it, the event would disappear, never to be seen again. Event bubbling simply passes these unhandled events to the parent element for handling. The event continues up ("bubbles up") the element hierarchy until it is handled, or until it reaches the topmost object, the document object.

Event bubbling is useful because it:

  • Allows multiple common actions to be handled centrally.
  • Reduces the amount of overall code in the Web page.
  • Reduces the number of code changes required to update a document.

The following is a simple example of event bubbling in action.


<HTML>
<BODY>
<DIV id=OuterDiv style="background-color: red" onmouseover="alert(window.event.srcElement.id);">
This is some text
<IMG id=InnerImg>
</DIV>
</BODY>
</HTML>

Click to view sample.

On this page, when the user moves the mouse pointer over the text, the text "OuterDiv" appears in a dialog box. If the user moves the mouse pointer over the image, the text "InnerImg" appears in a dialog box.

Notice that the onmouseover event for the img object was handled even though it does not have an event handler. Why is this? The onmouseover event from the img object bubbles up to its parent element, which is the div object. Because the div object has an event handler registered for the onmouseover event, it fires and generates the specified dialog window.

Every time an event is fired, a special property on the window object is created. This special property contains the event object. The event object contains context information about the event that just fired, including mouse location, keyboard status, and, most importantly, the source element of the event.

The source element is the element that causes the event to fire, and is accessed using the srcElement property on the window.event object.

In the preceding example, the dialog box displays the id property of the event's srcElement.

Handling Rollover Effects

An author creates a rollover effect to make part of a page react when the user moves the mouse pointer over it. With Internet Explorer 4.0, the process of creating a rollover effect is greatly simplified.


<HTML>
<HEAD>
<STYLE>
.Item {
   cursor: hand;
   font-family: verdana; 
   font-size: 20;
   font-style: normal;
   background-color: blue;
   color: white
 }
.Highlight {
   cursor: hand; 
   font-family: verdana;
   font-size: 20;
   font-style: italic;
   background-color: white;
   color: blue
 }
</STYLE>
</HEAD>
<BODY>
<SPAN class=Item>Milk</SPAN>
<SPAN class=Item>Cookies</SPAN>
<SPAN class=Item>Eggs</SPAN>
<SPAN class=Item>Ham</SPAN>
<SPAN class=Item>Cheese</SPAN>
<SPAN class=Item>Pasta</SPAN>
<SPAN class=Item>Chicken</SPAN>

<SCRIPT>
function rollon() {
  if (window.event.srcElement.className == "Item") {
     window.event.srcElement.className = "Highlight";
  }
}

document.onmouseover = rollon;

function rolloff() {
  if (window.event.srcElement.className == "Highlight") {
     window.event.srcElement.className = "Item";
  }
}

document.onmouseout = rolloff;
</SCRIPT>
</BODY>
</HTML>

Click to view sample.

In the preceding example, seven span objects are initially set to use the class Item. When the mouse pointer moves over any one of those elements, it will be changed to use the class Highlight.

Innovations in Internet Explorer 4.0 enable the following:

  • Events now can be generated from a span object. Previously, an author would have had to wrap each span in an anchor to get the right events.
  • With event bubbling, events can be captured at the document object level. You do not need to create separate event handlers for each element that participate in the effect. For example, should the author add HTML to the page, these additional elements will participate in the event model without changing a single line of script. Notice that the document object is the "super parent" for all elements in the document body.

Canceling Events

All events bubble to their parent element (and, recursively, all the way up to the document object) unless the event is canceled. To cancel an event, you must set the window.event.cancelBubble property to "true" in the event handler. Note that unless canceled, events will bubble up the hierarchy and be handled by all parent elements registered to the event, even if the event has already been handled.

Canceling event bubbling should not be confused with canceling the default action for the event. Some events (for example, the onclick event on an anchor) have a default action. When an anchor is clicked, its default action is to navigate the current window to the URL specified in the src property. Returning "false" from an event handler, or setting window.event.returnValue to "false", cancels the default action but does not cancel event bubbling unless window.event.cancelBubble is also set. Conversely, canceling an event's bubbling doesn't cancel its default action.

The last example shows how to use event bubbling to apply a common effect to a set of elements. If you want to exclude an element from that effect, simply change the following line of code, from:


<SPAN class=Item>Ham</SPAN>

to:


<SPAN class=Item onmouseover="window.event.cancelBubble = true;"
    onmouseout="window.event.cancelBubble = true;">Ham</SPAN>

Click to view sample.

No matter how many times the user moves the mouse pointer over the word Ham, it will not change style. This is because both the onmouseover and onmouseout events are canceled; they did not bubble through to the document, so the document was never given the opportunity to handle those events for the word Ham.

Special Considerations

At any one time, you can have an onmouseover event only on a single object. Consider the following case:


<DIV id=MyDiv>
<IMG id=MyImg>
</DIV>

If you were to move your mouse pointer over the img, the order of events would be as follows:


MyDiv:: onmouseover
MyDiv:: onmouseout
MyImg:: onmouseover

Moving your mouse pointer off the img fires the MyDiv::onmouseover event again.

At times, the author might want to detect when the mouse pointer moves outside a div to perform a special effect. It is not enough to simply trap the onmouseout event. To make this easier, Internet Explorer 4.0 indicates the source element (fromElement) and target element (toElement) for the onmouseover and onmouseout events. You can use these properties in combination with the contains method to tell when the mouse pointer moves outside a region.

The following example shows how to use these properties and methods.


<HTML>
<BODY id=Body>
<DIV id=OuterDiv style="width: 100px; height: 50px; background: red" 
    onmouseover="over();" onmouseout="out();">
<IMG id=Img1>
<IMG id=Img2>
<IMG id=Img3>
</DIV>
<SCRIPT>
function over() {
    var s;
    s = "onmouseover: "+window.event.srcElement.id+" from: "+

window.event.fromElement.id+" to: "+window.event.toElement.id;
    alert(s);
}

function out() {
    var s;
    s = "onmouseout: "+window.event.srcElement.id+" from: "+

window.event.fromElement.id+" to: "+window.event.toElement.id;
    alert(s);

    if (!(OuterDiv.contains(window.event.toElement))) {
        alert("Out Now");
    }
}
</SCRIPT>

</BODY>
</HTML>

Click to view sample.

Related topics

Working with Windows, Frames, and Dialog Boxes
Scripting with Elements and Collections
Understanding the Event Model
About Cross-Frame Scripting and Security

 

 

Show:
© 2014 Microsoft