You are on page 1of 31

About the DHTML Object Model

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? 


 Accessing Elements with Script 
 Events: Bubbling, Canceling, and Handling 
 Handling Rollover Effects 
 Canceling Events 
 Special Considerations 
 Related Topics

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

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

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 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 event Generated 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 Generated when the user:
event
onkeypress Presses and releases a key (full down-and-up cycle). However, if a key is held down,
multipleonkeypress 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.

Copy

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

Code
example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/overview/dom_01.htm

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

Copy

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

Code
example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/overview/dom_02.htm

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 settingwindow.event.returnValue to "false", cancels the default action but does
not cancel event bubbling unlesswindow.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:

Copy

<SPAN class=Item>Ham</SPAN>

to:

Copy

<SPAN class=Item onmouseover="window.event.cancelBubble = true;"


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

Code
example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/overview/dom_03.htm

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:

Copy

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

Copy

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.

Copy

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

Collection

all Collection
Returns a reference to the collection of elements contained by the object.

Syntax

[ collAll = ] object .all
[ oObject = ] object .all( vIndex [, iSubIndex ] )

Possible Values

collAll Array of elements contained by the object.


oObject Reference to an individual item in the array of elements contained by the object.
vIndex Required. Integer or string that specifies the element or collection to retrieve. If
this parameter is an integer, the method returns the element in the collection at the
given position, where the first element has value 0, the second has 1, and so on. If
this parameter is a string and there is more than one element with
the name or id property equal to the string, the method returns a collection of
matching elements.
iSubInde Optional. Position of an element to retrieve. This parameter is used when vIndex is
x a string. The method uses the string to construct a collection of all elements that
have a name or idproperty equal to the string, and then retrieves from this
collection the element at the position specified by iSubIndex.

Members Table

The following table lists the members exposed by the all object.

Attributes/Properties

Property Description
length Gets or sets the number of objects in a collection.
Methods

Method Description
item Retrieves an object from various collections, including the all collection.
namedItem Retrieves an object or a collection from a specified collection.
tags Retrieves a collection of objects that have the specified HTML tag name.
urns Retrieves a collection of all objects to which a specified behavior is attached.

Remarks

The all collection includes one element object for each valid HTML tag. If a valid tag has a matching end
tag, both tags are represented by the same element object.

The collection returned by the document's all collection always includes a reference to the HTML, HEAD,


and TITLE objects regardless of whether the tags are present in the document. If the BODY tag is not
present, but other HTML tags are, a BODY object is added to the all collection.

If the document contains invalid or unknown tags, the collection includes one element object for each.
Unlike valid end tags, unknown end tags are represented by their own element objects. The order of the
element objects is the HTML source order. Although the collection indicates the order of tags, it does not
indicate hierarchy.

The name property only applies to some elements such as form elements. If the vIndex is set to a string
matching the value of a name property in an element that the name property does not apply, then that
element will not be added to the collection.

Examples

This example, in Microsoft JScript (compatible with ECMA 262 language specification), shows how to
display the names of all tags in the document in the order the tags appear in the document.

Copy

for(i = 0; i < document.all.length; i++){


alert(document.all(i).tagName);
}

This example, also in JScript, shows how to use the item method on the all collection to retrieve all
element objects for which the name property or ID attribute is set to sample. Depending on the number
of times the name or ID is defined in the document, the item method returns null, a single element
object, or a collection of element objects. The value of the length property of the collection determines
whether item returns a collection or a single object.

Copy

var oObject = document.all.item("sample");


if (oObject != null){
if (oObject.length != null){
for (i = 0; i < oObject.length; i++){
alert(oObject(i).tagName);
}
}
else{
alert(oObject.tagName);
}
}

children Collection
Retrieves a collection of DHTML Objects that are direct descendants of the object.

Syntax

[ oColl  = ] object .children
[ oObject = ] object .children( vIndex [, iSubIndex ] )

Possible Values

oColl Array containing the direct descendants of an object.


oObject Reference to an individual item in the array of elements contained by the object.
vIndex Required. Integer or string that specifies the element or collection to retrieve. If
this parameter is an integer, the method returns the element in the collection at the
given position, where the first element has value 0, the second has 1, and so on. If
this parameter is a string and there is more than one element with
the name or id property equal to the string, the method returns a collection of
matching elements.
iSubInde Optional. Position of an element to retrieve. This parameter is used when vIndex is
x a string. The method uses the string to construct a collection of all elements that
have a name or idproperty equal to the string, and then retrieves from this
collection the element at the position specified by iSubIndex.

Members Table

The following table lists the members exposed by the children object.

Attributes/Properties

Property Description
constructor Returns a reference to the constructor of an object.
length Gets or sets the number of objects in a collection.
Methods
Method Description
item Retrieves an object from various collections, including the all collection.
tags Retrieves a collection of objects that have the specified HTML tag name.
urns Retrieves a collection of all objects to which a specified behavior is attached.

Remarks

Similar to the objects contained in the all collection, the objects contained in the children collection are
undefined if the child elements are overlapping tags.

The children collection can contain HTML elements.

Example

This example shows how to retrieve a collection of DHTML Objects using script. The children collection
for oParentDIV includes input type=text, div and button. The children collection
for oChildDIV includesp.

Copy

<HTML>
<HEAD>
...
<SCRIPT>
var oColl; //Collection for children.
var oRow, oCell; //Use for row and cell.
function fnCollection(){
oColl = oParentDIV.children;

//Call function to create cells for the top parent object.


getChildren(oColl, oParentDIV);

/*Call function to create cells for the child within the parent object
containing its own child.*/
oColl = oChildDIV.children;
getChildren(oColl, oChildDIV);
}
/*****************************************************************************
In:
oColl - Collection of children.
oCollection - Parent object.
Out:
Output to screen.
******************************************************************************/
function getChildren(oColl, oCollection){
for(x=0;x<oColl.length;x++){
//Create new row.
oRow = oTable.insertRow();
//Create cell with the array index of current child.
oCell = oRow.insertCell();
oCell.align = 'center';
oCell.style.color = '#0000FF';
oCell.innerText = x;

//Create cell with the tagName of current child.


oCell = oRow.insertCell();
oCell.align = 'center';
oCell.innerText = oCollection.children.item(x).tagName;

//Create cell with ID / name of current child.


oCell = oRow.insertCell();
oCell.align = 'center';
if(oCollection.children.item(x).name != null){
oCell.innerText = oCollection.children.item(x).name;
}else{
oCell.innerText = oCollection.children.item(x).id;
}

//Create cell with applicable Parent object to the child.


oCell = oRow.insertCell();
oCell.align = 'center';
oCell.innerText = oCollection.id;
}
}
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<SPAN class="oTitle">DIV Object (ID: oParentDIV)</SPAN>
<DIV id="oParentDIV" class="oDIV">
Some Input (non-editable): <INPUT type="text" name="SomeInputTextBox"
value="" size="5" CONTENTEDITABLE="false">
<DIV id="oChildDIV">
<P id="oParagraph1">Some text in a paragraph</P>
</DIV>
<BUTTON name="SomeButton" onclick="alert('Some alert.');">The Label for
the Button</BUTTON>
</DIV>
<HR>
<BUTTON id="b1" onclick="fnCollection(); b1.disabled=true;"
style="cursor:hand">Retrieve Collection</BUTTON>
<BR><BR>

<TABLE border="1" id="oTable" alt="Child Listing">


<TR>
<TH>Array Index</TH><TH>Child Element</TH><TH>ID</TH><TH>Parent Object</TH>
</TR>
</TABLE>
</CENTER>
</BODY>
</HTML>
onclick Event
[This documentation is preliminary and is subject to change.]

Fires when the user clicks the left mouse button on the object.

Syntax

Inline HTML <ELEMENT onclick = "handler(event);" >

Event object.onclick = handler;
Property
DOM Events object.addEventListener( "click", handler, bCapture Internet Explorer 9   
);

attachEvent object.attachEvent( "onclick", handler); Internet Explorer


only

Event Information

Bubbles Yes

Cancels Yes

To  Click the object.


invoke  Invoke the click method.
 Press the ENTER key in a form.
 Press the access key for a control.
 Select an item in a combo box or list box by clicking the left mouse button
or by pressing the arrow keys and then pressing the ENTER key.

Default Initiates any action associated with the object. For example, if the user clicks
action an a object, the browser loads the document specified by the href property. To
cancel the default behavior, set the returnValue property of the event object to
FALSE.

Event Object Properties

    In Internet Explorer 9, the type of event object depends on whether you use attachEvent
oraddEventListener to register the event handler. If you register the handler with addEventListener, an
object of type MouseEvent is passed during the event. If you use attachEvent, the legacy event object is
passed instead.

Available Properties
button Gets or sets the mouse button pressed by the user.

clientX Gets or sets the x-coordinate of the mouse pointer's position relative to the client
area of the window, excluding window decorations and scroll bars.

clientY Gets or sets the y-coordinate of the mouse pointer's position relative to the client
area of the window, excluding window decorations and scroll bars.

ctrlKey Gets or sets the state of the CTRL key.

offsetX Gets or sets the x-coordinate of the mouse pointer's position relative to the
object firing the event.

offsetY Gets or sets the y-coordinate of the mouse pointer's position relative to the
object firing the event.

screenX Gets or sets the x-coordinate of the mouse pointer's position relative to the user's
screen.

screenY Gets or sets the y-coordinate of the mouse pointer's position relative to the user's
screen.

shiftKey Gets the state of the SHIFT key.

srcElemen Gets or sets the object that fired the event.


t
x Gets or sets the x-coordinate (in pixels) of the mouse pointer's offset from the
closest relatively positioned parent element of the element that fired the event.

y Gets or sets the y-coordinate (in pixels) of the mouse pointer's offset from the
closest relatively positioned parent element of the element that fired the event.

Refer to the specific event object for additional event properties.

Remarks

If the user clicks the left mouse button, the onclick event for an object occurs only if the mouse pointer is
over the object and an onmousedown and an onmouseup event occur in that order. For example, if the
user clicks the mouse on the object but moves the mouse pointer away from the object before releasing,
no onclick event occurs.

The onclick event changes the value of a control in a group. This change initiates the event for the group,
not for the individual control. For example, if the user clicks a radio button or check box in a group,
theonclick event occurs after the onbeforeupdate and onafterupdate events for the control group.

If the user clicks an object that can receive the input focus but does not already have the focus,
theonfocus event occurs for that object before the onclick event. If the user double-clicks the left mouse
button in a control, an ondblclick event occurs immediately after the onclick event.
Although the onclick event is available on a large number of HTML elements, if a Web page is to be
accessible to keyboard users, you should restrict its use to the a, input, area, and button elements. These
elements automatically allow keyboard access through the TAB key, making Web pages that use the
elements accessible to keyboard users. For more information, please see the section on writing accessible
Dynamic HTML.

Examples

This example uses the event object to gain information about the origin of the click. In addition, it cancels
the default action to prevent navigation of anchor elements, unless the SHIFT key is pressed. Normally a
Shift+Click opens the target of a link in a new browser window; however, the script replaces the current
page by setting the location of the window object.

Copy

<script type="text/javascript">
/* This code cancels the event. If the click occurs in an anchor
and the SHIFT key is down, the page is navigated. */
function clickIt()
{
var e = window.event.srcElement
txtName.value = e.tagName;
txtType.value = e.type;

if ((e.tagName == "A") &&


(window.event.shiftKey)) {
window.location.href = e.href;
}

window.event.returnValue = false;
}
</script>
<body onclick="clickIt()">
<p>To follow a link, click while pressing the SHIFT key.</p>
<a href="about:blank">Click Here</a>
<textarea name="txtName"></textarea> <textarea name="txtType"></textarea>
</body>

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/onclickEX.htm

This example shows how to bind the onclick event to grouped controls.

Copy

<head>
<script type="text/javascript">

function CookieGroup()
{
txtOutput.value = window.event.srcElement.value;
}
</script>
</head>

<body>

<!-- Controls are grouped by giving them the same NAME but unique IDs. -->
<p>Grouped Radio Buttons<br>
<input type="radio"
name="rdoTest"
id="Cookies"
value="accept_cookies"
checked
onclick="CookieGroup()"><br>
<input type="radio"
name="rdoTest"
id="NoCookies"
value="refuse_cookies"
onclick="CookieGroup()"><br>
</p>
<p>Ungrouped Radio Button<br>
<input type="radio"
name="rdoTest1"
value="chocolate-chip_cookies"
onclick="CookieGroup()"><br>
</p>
<p>Value of control on which the onclick event has fired<br>
<textarea name="txtOutput" style="width: 250px"></textarea> </p>

</body>

onload Event
[This documentation is preliminary and is subject to change.]

Fires immediately after the browser loads the object.

Syntax

Inline HTML <ELEMENT onload = "handler(event);" >

Event object.onload = handler;
Property
DOM Events object.addEventListener( "load", handler, bCapture) Internet Explorer 9  
;

attachEvent object.attachEvent( "onload", handler); Internet Explorer


only

Event Information
Bubbles No

Cancels No

To invoke Open a page in the browser to invoke this event for the document or any
object within it.

Default Loads the object for which the event is specified.


action

Event Object Properties

    In Internet Explorer 9, the type of event object depends on whether you use attachEvent
oraddEventListener to register the event handler. If you register the handler with addEventListener, an
object of type Event is passed during the event. If you use attachEvent, the legacy event object is passed
instead.

Refer to the specific event object for additional event properties.

Remarks

The browser loads applications, embedded objects, and images as soon as it encounters
the applet,embed, and img objects during parsing. Consequently, the onload event for these objects
occurs before the browser parses any subsequent objects. To ensure that an event handler receives
the onload event for these objects, place the script object that defines the event handler before the
object and use theonload attribute in the object to set the handler.

The onload attribute of the body object sets an onload event handler for the window. This technique of


calling the window onload event through the body object is overridden by any other means of invoking
the window onload event, provided the handlers are in the same script language.

Examples

This example uses an onload event handler to display a message in the window's status bar when the
page has finished loading.

Copy

<body>
<script for="window" event="onload" language="JScript">
window.status = "Page is loaded!";
</script>
</body>

This example sets an onload event handler for an img object. The handler uses the event object to
retrieve the URL of the image.

Copy
<script>
function imageLoaded()
{
window.status = "Image " + event.srcElement.src + " is loaded";
}
</script>
<body>
<img src="sample.gif" onload="imageLoaded()"/>
</body>

onmouseover Event
[This documentation is preliminary and is subject to change.]

Fires when the user moves the mouse pointer into the object.

Syntax

Inline HTML <ELEMENT onmouseover = "handler(event);" >

Event object.onmouseover = handler;
Property
DOM Events object.addEventListener( "mouseover", handler, bCap Internet Explorer
ture); 9  

attachEvent object.attachEvent( "onmouseover", handler); Internet Explorer


only

Event Information

Bubbles Yes

Cancels Yes

To invoke Move the mouse pointer into an object.

Default action Initiates any action associated with this event.

Event Object Properties

    In Internet Explorer 9, the type of event object depends on whether you use attachEvent
oraddEventListener to register the event handler. If you register the handler with addEventListener, an
object of type MouseEvent is passed during the event. If you use attachEvent, the legacy event object is
passed instead.
Available Properties

button Gets or sets the mouse button pressed by the user.

clientX Gets or sets the x-coordinate of the mouse pointer's position relative to the client
area of the window, excluding window decorations and scroll bars.

clientY Gets or sets the y-coordinate of the mouse pointer's position relative to the client
area of the window, excluding window decorations and scroll bars.

ctrlKey Gets or sets the state of the CTRL key.

offsetX Gets or sets the x-coordinate of the mouse pointer's position relative to the
object firing the event.

offsetY Gets or sets the y-coordinate of the mouse pointer's position relative to the
object firing the event.

screenX Gets or sets the x-coordinate of the mouse pointer's position relative to the user's
screen.

screenY Gets or sets the y-coordinate of the mouse pointer's position relative to the user's
screen.

shiftKey Gets the state of the SHIFT key.

srcElemen Gets or sets the object that fired the event.


t
x Gets or sets the x-coordinate (in pixels) of the mouse pointer's offset from the
closest relatively positioned parent element of the element that fired the event.

y Gets or sets the y-coordinate (in pixels) of the mouse pointer's offset from the
closest relatively positioned parent element of the element that fired the event.

Refer to the specific event object for additional event properties.

Remarks

The event occurs when the user moves the mouse pointer into the object, and it does not repeat unless
the user moves the mouse pointer out of the object and then back into it.

Examples

This example uses the onmouseover event to apply a new style to an object.

Copy

<p
onmouseover="this.style.color='red'"
onmouseout="this.style.color='black'">
Move the mouse pointer over this text to change its color. Move the pointer
off the text
to change the color back.
</p>

This example shows how to change the value of a text area in response to mouse events.

Copy

<p>Move the mouse pointer into the text area to fire the onmouseover event. Move
it out to clear the text.
<textarea name="txtMouseTrack"
onmouseover="this.value='onmouseover fired'"
onmouseout="this.value=''">
</textarea></p>

onmouseout Event
[This documentation is preliminary and is subject to change.]

Fires when the user moves the mouse pointer outside the boundaries of the object.

Syntax

Inline HTML <ELEMENT onmouseout = "handler(event);" >

Event object.onmouseout = handler;
Property
DOM Events object.addEventListener( "mouseout", handler, bCapt Internet Explorer 9   
ure);

attachEvent object.attachEvent( "onmouseout", handler); Internet Explorer


only

Event Information

Bubbles Yes

Cancels No

To invoke Move the mouse pointer out of an object.

Default action Initiates any action associated with this event.

Event Object Properties


    In Internet Explorer 9, the type of event object depends on whether you use attachEvent
oraddEventListener to register the event handler. If you register the handler with addEventListener, an
object of type MouseEvent is passed during the event. If you use attachEvent, the legacy event object is
passed instead.

Available Properties

button Gets or sets the mouse button pressed by the user.

clientX Gets or sets the x-coordinate of the mouse pointer's position relative to the client
area of the window, excluding window decorations and scroll bars.

clientY Gets or sets the y-coordinate of the mouse pointer's position relative to the client
area of the window, excluding window decorations and scroll bars.

ctrlKey Gets or sets the state of the CTRL key.

offsetX Gets or sets the x-coordinate of the mouse pointer's position relative to the
object firing the event.

offsetY Gets or sets the y-coordinate of the mouse pointer's position relative to the
object firing the event.

screenX Gets or sets the x-coordinate of the mouse pointer's position relative to the user's
screen.

screenY Gets or sets the y-coordinate of the mouse pointer's position relative to the user's
screen.

shiftKey Gets the state of the SHIFT key.

srcElemen Gets or sets the object that fired the event.


t
x Gets or sets the x-coordinate (in pixels) of the mouse pointer's offset from the
closest relatively positioned parent element of the element that fired the event.

y Gets or sets the y-coordinate (in pixels) of the mouse pointer's offset from the
closest relatively positioned parent element of the element that fired the event.

Refer to the specific event object for additional event properties.

Remarks

When the user moves the mouse over an object, one onmouseover event occurs, followed by one or
more onmousemove events as the user moves the mouse pointer within the object.
One onmouseoutevent occurs when the user moves the mouse pointer out of the object.

Examples
This example uses the onmouseout event to apply a new style to an object.

Copy

<body>

<p onmouseout="this.style.color='black';"
onmouseover="this.style.color='red';">
Move the mouse pointer over this text to change its color.
Move the pointer off the text to change the color back.
</p>

</body>

This example shows how to swap images on mouse events.

Copy

<head>
<script type="text/javascript">
function flipImage(url)
{
if (window.event.srcElement.tagName == "img" )
{
window.event.srcElement.src = url;
}
}
</script>
</head>

<body>

<p>Move the mouse over the image to see it switch.</p>


<p>
<img src="/workshop/graphics/prop_ro.gif"
onmouseover="flipImage('/workshop/graphics/prop_rw.gif');"
onmouseout="flipImage('/workshop/graphics/prop_ro.gif');">
</p>

</body>

About Microsoft Tabular Data Control


The Tabular Data Control (TDC) is a Microsoft ActiveX control that can be hosted by Microsoft Internet
Explorer 4.0 and later to display data stored in a delimited text file. Using the TDC, a Web author can
display data either within tables or within controls found in a form. (Extensions in Internet Explorer 4.0 and
later allow you to bind data to HTML elements on the page as well as to repeat the content of an
HTML table element for each record of a data set. The latter can be thought of as using the table as a
template for the data, where the template is repeated once for each record.)

One of the primary features of the TDC is that it brings filtering and sorting operations to the client side
(there are no server-side operations).
The TDC exposes the OLE-DB simple provider interfaces. For more information about these interfaces,
see OLE-DB Simple Provider: A Data Binding API for MSHTML.

 Source Availability 
 Licensing and Distribution 
 Dependencies 
 Understanding the Tabular Data Control Object Model 
o File Properties 
o Filtering Properties 
o Sorting Properties 
 Using the Tabular Data Control 
o A Simple Before-and-After Example 
o Adding data to your Web page 
o Declaring the TDC object 
o Relaxing TDC Security 
o A More Advanced Example: Sorting and Filtering 
 Summary 

Source Availability
To aid developers in creating their own data source objects, the Tabular Data Control is provided as a
sample that ships with the Internet Client SDK. The source code can be found in \inetsdk\samples\tdc.

Licensing and Distribution


The Microsoft Tabular Data Control is automatically installed as part of the base installation of Internet
Explorer 4.0 and later.

Dependencies
The TDC is found in the file Tdc.ocx, which is automatically installed and registered with all versions of
Internet Explorer 4.0 and later.

Understanding the Tabular Data Control Object Model


The TDC supports properties and methods that can be divided into these categories:

 Elements that describe the data file.


 Elements that support data filtering.
 Elements that support data sorting.
File Properties

Most of the properties supported by the TDC are data-file properties. These properties specify the
location of the data file, the language used to create the data file, the character used to delimit fields, and
so on. The following list describes each property:

Property Description

CharSet Identifies the character set used by the data file. The default character set is latin1.
DataURL Specifies the location of the data file as a URL.
EscapeChar Identifies the character to be used as an escape character in the data file. There is no default escape
character.
FieldDelim Identifies the character that is used to mark the end of a field in the data file. The default character is
the comma (,).
Language Specifies the language used to generate the data file (this specifier uses the HTML standard codes
based on ISO 369). The default specifier is eng-us.
TextQualifier Specifies the optional character that surrounds a field.
RowDelim Identifies the character used to mark the end of each row of data. The default character is the
newline (NL) character.
UseHeader Specifies whether the first line of the data file contains header information. The default value is
FALSE.

Filtering Properties

One TDC property and one method apply to data filtering.

Set the Filter property to an expression that includes the name of the column to be filtered, the criteria for
filtering, and the value that will be compared against the specified column using the given value. The
default value is an empty string ("").

Call the Reset method to apply the filter and refresh the contents of the HTML elements bound to the
data supplied by the TDC.

Sorting Properties

One TDC property and a single TDC method apply to data sorting.

Set the Sort property to a semicolon-delimited list of column names by which the bound HTML elements
should be sorted. Prefixing a column name with a plus (+) symbol indicates ascending order. The minus (-)
symbol indicates descending order. The default sort order is ascending.
Call the Reset method to apply the new sort order and to refresh the contents of the HTML elements
bound to the data supplied by the TDC.

Using the Tabular Data Control


This section demonstrates how you can incorporate the TDC into your Web pages.

Note  The TDC examples in this section require Internet Explorer 4.0 and later.

A Simple Before-and-After Example

This section contains a very simple example demonstrating how you can replace a static table in your
HTML page with a dynamic table that is generated using the TDC. When this replacement occurs, you'll no
longer need to modify your HTML source file each time your data changes; instead, you can simply
modify the data file or regenerate it from a database.

Adding data to your Web page

The Tabular Data Control (TDC) has many uses, but perhaps the easiest way to get a feel for its capabilities
is to see a short example. If you have a data file containing some of the elements of the periodic table, it
might look like this:

Copy

Element,Symbol
Hydrogen,H
Helium,He
Lithium,Li
Beryllium,Be
Boron,B
Carbon,C
Nitrogen,N
Oxygen,O
Fluorine,F
Neon,Ne

Each line contains the name of the element followed by a comma, and then its scientific abbreviation. If
you wanted to display this table in a Web page without using the TDC, you would add the table tags
around each word, as shown in the following example:

Copy

<TABLE>
<THEAD><TR><TD>Element</TD><TD>Symbol</TD></TR></THEAD>
<TBODY>
<TR><TD>Hydrogen</TD> <TD>H</TD></TR>
<TR><TD>Helium</TD> <TD>He</TD></TR>
<TR><TD>Lithium</TD> <TD>Li</TD></TR>
<TR><TD>Beryllium</TD> <TD>Be</TD></TR>
<TR><TD>Boron</TD> <TD>B</TD></TR>
<TR><TD>Carbon</TD> <TD>C</TD></TR>
<TR><TD>Nitrogen</TD> <TD>N</TD></TR>
<TR><TD>Oxygen</TD> <TD>O</TD></TR>
<TR><TD>Fluorine</TD> <TD>F</TD></TR>
<TR><TD>Neon</TD> <TD>Ne</TD></TR>
</TBODY>
</TABLE>

Click the Show Me button to see how the previous table appears when viewed in your browser.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/databind/eltstat.htm

A static table is not only tedious to create, but it also makes it inconvenient to edit or update the data.
This especially applies if you want to use the raw data file in other applications. Using the TDC, you can
instead tell the Web page where to find the text file, and it will read the data directly from the file (plus
optionally sort it, filter it, and skip columns). The previous table coding is replaced with the following
coding:

Copy

<TABLE datasrc=#elements>
<THEAD><TR><TD>Element</TD><TD>Symbol</TD></TR></THEAD>
<TBODY>
<TR><TD><DIV datafld="Element"></DIV></TD><TD><DIV datafld="Symbol"></DIV></TD></TR>
</TBODY>
</TABLE>

Click the Show Me button to see how data binding can be used to replace a static table in Internet
Explorer 4.0 and later.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/databind/eltdyn.htm

If you look more closely at these changes, you will note that the first line uses the dataSrc attribute to
identify the TDC. (This identifier corresponds to the id attribute that was specified for the object element
that loaded the control.)

Copy

<TABLE datasrc=#elements>

The prepended # symbol is always required by the dataSrc attribute.

You can include multiple linked tables and objects in each Web page; each table should specify
a dataSrc attribute that can be unique to that table or shared between tables or other elements on the
page, such as forms.
The second line of the table definition is unchanged. As you can see, it provides the table heading.

Copy

<THEAD><TR><TD>Element</TD><TD>Symbol</TD></TR></THEAD>

The fourth line is the most interesting. Instead of providing the actual data, you specify the name of a
column in the data file using the new dataFld attribute.

Copy

<TR><TD><DIV datafld="Element"></DIV></TD><TD><DIV datafld="Symbol"></DIV></TD></TR>

Because the original data file had a header that specified the name of each column, these column names
can be used. If no header is provided in your data file, you should use the default names of Column1,
Column2, and so on.

As part of the header that specifies column names, a type specifier can be included indicating the data
type of the column. Since the TDC reads its data from a text file, this indicates the appropriate type
conversion to do upon reading the data from the file. The TDC uses this to perform accurate sorting and
filtering. Consider the case where you have integers in a column and you request the column to be sorted.
Without the type specification, the sort would be done using string (lexicographic) ordering, which would
give the wrong result. For more information on specifying data types for columns, see TDC Reference.

With this information encoded in the table, Internet Explorer 4.0 and later will ask the TDC for data to put
into the table. It will then create one new row for each row of data. Notice how all the other table
encoding tags remain unchanged. In fact, you can treat the incoming data exactly as if it were text that
you hard-coded into your Web page. For example, if you wanted the symbols in the table to be bold and
centered in their column, you could change the table entry to the following:

Copy

<TD><CENTER><DIV datafld="Symbol"></DIV></CENTER></TD>

You could also choose to completely leave out the symbol information from the table just by removing
the <DIV> entry where it is specified. Although this might not necessarily be appropriate for this example,
it's often convenient to omit some fields because that allows you to reuse the same data file in many
different Web pages rather than maintaining multiple copies of almost identical data.

Declaring the TDC object

The only other new entry in your Web page is the TDC object declaration. The above examples use the
following:

Copy
<OBJECT id=elements CLASSID="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83">
<PARAM NAME="DataURL" VALUE="minielts.txt">
<PARAM NAME="UseHeader" VALUE="True">
</OBJECT>

The id attribute identifies the TDC and its associated data for later use by elements such as tables, forms,
and scripting. The id attribute can be any arbitrary name, but it's best to start with a letter and avoid
spaces and punctuation characters.

The DataURL property tells the TDC where to find the data file. You can provide any valid URL, or, as in
this example, use a relative URL that will cause the TDC to look in the same place your Web page was
found. Other valid DataURLsettings include the following:

Copy

<PARAM NAME="DataURL" VALUE="data/elements.txt">


<PARAM NAME="DataURL" VALUE="http://www.mycoolsite.com.au/elements.txt">
<PARAM NAME="DataURL"
VALUE="file://\\intranet\server\buried\down\a\long\path\elements.txt">

DataURL is the only property required by the TDC to access data. To delay the binding, omit the
specification of theDataURL property in the object declaration, and set it later in script code.

The UseHeader property indicates whether the first line of the data file identified by DataURL lists the
names of the fields. In the example text file above, the first line was:

Copy

Element,Symbol

This isn't part of the data. Instead, it identifies the names of the columns in the data set. Because the
default value of this property is FALSE, the UseHeader property must be set to TRUE.

The Tabular Data Control (TDC) determines the codepage for the source data file incorrectly in certain
scenarios. The problem can occur if the ambient codepage is Unicode, in which case the TDC assumes
that the bound data is also Unicode, which is not necessarily true. When the TDC attempts to identify the
Unicode signature in the byte-reversed case, it compares the value incorrectly. If the TDC reads a variable
that is uninitialized, it waits for an excessive period of time in an attempt to identify the ambient
codepage. If the TDC changes its codepage because it sees a Unicode signature, it fails to update
its CharSet property. Therefore, to avoid potential problems associated with incorrect codepage
identification, the CharSet property can be set explicitly when declaring the TDC, as shown in the
following example.

Copy

<OBJECT classid=CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83>
<PARAM NAME="CharSet" VALUE="iso-8859-1" / >
</OBJECT>

Relaxing TDC Security

By default, if the DataURL property specifies a URL on a different domain than that of the Web page, the
TDC will silently fail to load the data. This feature prevents unauthorized pages or untrusted scripts from
using the TDC to access private data. To allow content providers to create pages that access data on a
different domain, providers can insert a domain string in the data. The string begins with "@!
allow_domains" and is followed by a semicolon-delimited list of domain names and/or IP addresses. The
string must appear exclusively at the beginning of the first line in the data set with no preceding white-
space. The exact specification for the format string is as follows:

Copy

domain_string: header_string "=" domain_list


header_string: "@!allow_domains"
domain_list: domain_spec [; domain_list ]
domain_spec: * | [*.] domain | ipaddr

Observe that while wildcards may be used in domain names (*.microsoft.com), they are not supported in
IP addresses.

The following is an example of a domain string that could be embedded in a data set to enable a page
hosted on all microsoft.com and investor.msn.com servers to access the data.

Copy

@!allow_domains=*.microsoft.com; investor.msn.com

A More Advanced Example: Sorting and Filtering

The example behind the following Show Me button demonstrates how you can automate the sorting and
filtering of data in a table. Using the chemistry theme, the example displays a table that contains the first
five periods of the periodic table. You can sort the data by clicking any of the three table headings
(Position, Element, or Symbol); you can filter the data by choosing a specific period and group from the
Period or Group list box.

Code example: http://samples.msdn.microsoft.com/workshop/samples/author/databind/eltadv.htm

Sorting data

Dynamic sorting is enabled using the Sort property and the Reset method on the TDC. In the previous
example, a VBScript function supports the onclick event for each column heading in the table. When the
user clicks a given heading, the corresponding function is called and the Sort property is assigned a value
prior to calling the Reset method. The following example shows the function that handles sorting for the
Symbol column.
Copy

function symbol_onclick()
elem_list.Sort = "+Symbol"
elem_list.Reset()
end function

In this example, the Sort property is assigned the name of the third column (Symbol), and then
the Reset method is called. The "+" indicates an ascending sort. A "-" prefix indicates a descending sort.

The following excerpt from the HTML source file for this example demonstrates how the column headings
were set up using the HTML div element.

Copy

<THEAD><TR>
<TD><DIV ID=position><U><FONT COLOR=BLUE>Position</FONT></U></DIV></TD>
<TD><DIV ID=element><U><FONT COLOR=BLUE>Element</FONT></U></DIV></TD>
<TD><DIV ID=symbol><U><FONT COLOR=BLUE>Symbol</FONT></U></DIV></TD>
</TR></THEAD>

Filtering data

Dynamic filtering is enabled using the Filter property and the Reset method of the TDC. In the example, a
VBScript function supports the onchange event for each drop-down list box that appears above the table.
When this function is invoked, a filter expression is constructed from the selected values in the Period and
Group combo boxes, the expression is assigned to the Filter property, and the Reset method is called to
synchronize the table displaying the data.

The following excerpt from the HTML source file shows the definition of the Period drop-down list box.

Copy

<SELECT ID=cboPeriod>
<OPTION SELECTED VALUE=0>ALL
<OPTION VALUE=1>1
<OPTION VALUE=2>2
<OPTION VALUE=3>3
<OPTION VALUE=4>4
<OPTION VALUE=5>5
</SELECT>

When a user selects a different value from either the Period drop-down or the Group drop-down, the
following VBScript function handles the resulting onchange event.

Copy
function FilterGroupAndPeriod()
cFilterExpr = Empty
if cboPeriod.selectedIndex > 0 then
cFilterExpr = "Period=" & cboPeriod.selectedIndex
end if
if cboGroup.selectedIndex > 0 then
if Not IsEmpty(cFilterExpr) then
cFilterExpr = cFilterExpr & " & "
end if
cFilterExpr = cFilterExpr & "Group=" & cboGroup.selectedIndex
elem_list.object.Filter = cFilterExpr
end if
elem_list.object.Filter = cFilterExpr
elem_list.Reset
end function

The code builds a single expression representing a filter on both the Period and the Group columns in the
data set. Notice that if the first value (ALL) is selected in either drop-down, the respective code will not
contribute to the filter expression. Also, note that if the user has selected both an explicit period and
group, the subexpressions are separated by " & ", indicating to the TDC that the records to be displayed
must meet both filter criteria. When the user selects "ALL" in both drop-downs, neither of the conditional
statements is executed, the filter expression remains empty, and all the data is displayed in the bound
table.

The final line in this function invokes the Reset method, which evaluates the filter expression, applies it to
the data set, and forces MSHTML to re-render the table in which the data is displayed.

Summary
This article has described the features of the Tabular Data Control, a simple read-only data source object
provided with Internet Explorer 4.0 and later. For more detailed information on the methods and
properties supported by this object, see the TDC Reference.

You might also like