Understanding the IE Object Model
Once the World Wide Web began to gain popularity, there was a great concern about preserving standards, so that the exchange of information would remain as open as possible. The Document Object Model (DOM), like HTML, is one of those standards. Basically, the Document Object Model provides a means for you to interact programmatically with the document displayed by the browser. Both Netscape Navigator and Internet Explorer have a document object model; however, there are some large differences between the two. Despite the presence of standards documents, there is always room for interpretation. (If you are interested in reading more about the Document Object Model standards, or any of the other standards that apply to the World Wide Web, see http://www.w3.org.)
We are going to take a look at the Internet Explorer Document Object Model. It is a rich environment that will allow you a measure of control over the document in the browser. Before we jump in, let's have a quick look at the Document Object Model itself and some of its parts. These are shown in Figure 8-3.
Figure 8-3. Internet Explorer Object Model
As you can see, the Window object is the parent of all of the other objects in this model. Each document will always have at least one Window object. A Window object will always have at least one Document object. Without the Document object, there would not be much for you to do with the Document Object Model. This figure shows the hierarchical nature of the Document Object Model. Like many of the object models that Visual Basic developers work with, you can access objects via their parent and use their properties to enhance your client-side development.
The object model is too extensive to document fully here. The next section displays some tables that describe the properties and methods of some of the objects that are programmatically available in the DOM. These tables are not exhaustive references to the objects; we have included the methods and properties that we consider to be the most useful and interesting. This will give you an idea of the scope and power of the Document Object Model.
8.3.1 The Window Object
The Window object is the top-level object in the object model. When you reference the Window object, you are actually interacting directly with the browser and the browser window itself. The Frame object in the object model is also just a particular type of Window object the same properties and methods that apply to the Window object apply to the Frame object as well.
Some of the Window object's significant properties are shown in Table 8-2; its methods appear in Table 8-3.
Property |
Description |
---|---|
clientInformation |
Returns the navigator (or clientInformation) object, which provides information about the browser. |
closed |
A Boolean value that can be checked to see if a window is still open. |
event |
Returns an event object that is accessible only from within an event handler. The event object itself conveys a wealth of information (such as mouse location or keyboard status) about the system environment when the event was fired. |
history |
Returns the History object for the current window or frame. |
location |
Sets or retrieves the URL of the document currently loaded in the window. |
name |
The name of a frame or window. |
parent |
Returns a reference to the parent window. |
screen |
Returns a reference to the screen object. |
status |
Returns or sets the text of the status bar in the browser. |
top |
Returns a reference to the browser window (i.e., the top-level Window object). |
Method |
Description |
---|---|
alert |
Displays a dialog box with a message. Its syntax is Window.alert sMsg where sMsg is an optional string containing the message. |
blur |
Removes the focus from the window and fires the onBlur event. Its syntax is Window.blur. |
clearTimeout |
Turns off the timeout delay counter set in a previous call to the setTimeout method. Its syntax is Window.clearTimeout iTimeoutID where iTimeoutID is the timeout setting returned by the previous call to setTimeout. |
close |
Closes the current window. Its syntax is Window.close. |
execScript |
Evaluates one or more script expressions in any scripting language embedded in the browser. Its syntax is Window.execScript sExpression,sLanguage, where sExpression is a string that specifies the code to be executed and sLanguage is an optional string that specifies the language of sExpression. The default value of sLanguage is JScript. |
focus |
Brings the window to the front of all regular browser windows and fires the onFocus event. Its syntax is Window.focus. |
navigate |
Loads a new document into the window or frame. Its syntax is Window.navigate sURL, where sURL is a string containing the URL of the document to be loaded. |
open |
Opens a new window (but does not close the original one). Its syntax is Window.open(sURL, sName, sFeatures, bReplace), where sURL is the optional URL of the document to be opened in the window (if absent, the browser will open its default document), sName is the optional name of a window used as the value of the TARGET attribute of the or tag, sFeatures is an optional string that can contain a wide array of window configuration features, and bReplace is an optional Boolean that indicates whether the new URL should replace the existing one in the browser's history list (True) or whether an entry should be added (False). The method returns a reference to the new Window object. |
|
Starts the printing process for the window or frame. Its syntax is Window.print. |
scroll |
Sets the scrolled position of the document inside the current window or frame. Its syntax is Window.scroll ix, iy, where ix and iy are the number of pixels to be offset horizontally and vertically in the upper-left corner of the window. |
showHelp |
Displays a help window with the document specified by the URL parameter. Its syntax is Window.showHelp sURL, vContextID where sURL is the URL of the help file and vContextID is an optional context identifier that identifies a particular item within the help file. |
8.3.2 The Document Object
The Document object represents the document displayed in a window or frame. Its properties are shown in Table 8-4 and its methods are listed in Table 8-5.
Property |
Description |
|
---|---|---|
activeElement |
Returns a reference to the object that currently has the focus within the document. |
|
alinkColor |
Retrieves or sets thecolor of the hypertext link as it is clicked. |
|
bgColor |
Retrieves or sets the background color of the element. |
|
body |
Returns a reference to the Body object defined by the |
element within the document. |
domain |
Returns or sets the hostname of the server that served up the document. |
|
fgColor |
Retrieves or sets the foreground color for the document. |
|
linkColor |
Retrieves or sets the color of a hypertext link that hasn't been visited. |
|
location |
Returns a location object that allows the URL of the current document to be retrieved or set. |
|
vlinkColor |
Retrieves or sets the color of a link that has been visited recently. |
Method |
Description |
---|---|
clear |
Removes the document from the window or frame. Its syntax is Document.clear. |
close |
Closes the document writing stream to a window or frame. Its syntax is Document.close. |
createStyleSheet |
Creates and adds a new stylesheet for the document. Its syntax is Document.createStyleSheet sURL, iIndex where sURL is an optional string that specifies whether to add style information as a Link object or as a Style object, and iIndex is an optional integer that indicates where the new stylesheet is to be inserted in the styleSheets collection. By default, it is inserted at the end of the collection. The method returns a reference to the new styleSheet object. |
open |
Opens a new window to receive output from the Write and WriteLn methods. Its syntax is Document.open(sMimeType, sReplace), where sMimeType must be "text/html," and sReplace is an optional string that indicates whether the new document replaces the existing one in the history list (True) or not (False, the default). The method returns the new Document object. |
write |
Allows for dynamic content to be added to the page. Must be called when the page is being opened. Its syntax is Document.write sText, where sText is the text and HTML to be written. |
8.3.3 The Elements Collection and HTML Intrinsic Controls
The Elements collection is a collection of all the HTML intrinsic objects contained in a form. You can access the Elements collection with a code fragment like the following:
Dim oElements Set oElements = Document.frmForm.Elements
where frmForm is the name of the form on which the Elements collection resides. The Elements collection has two read-only properties:
length
Indicates the number of HTML intrinsic controls in the collection.
Item
Retrieves a specific HTML intrinsic control based on either its name or its ordinal position in the collection, starting at 0. The highest ordinal position in the collection is one less than the value of the length property.
You can then access a particular control with a code fragment like:
Set oCtrl = Document.frmData.Elements.Item("txtName")
However, the Item property is the default member of the Elements collection, so this can be shortened to:
Set oCtrl = Document.frmData.Elements("txtName")
The default member of the Form collection is the Elements collection, though, so this statement can be further shortened to:
Set oCtrl = Document.frmData("txtName")
or, even more clearly:
Set oCtrl = Document.frmData.txtName
Unfortunately, the way in which you programmatically work with an HTML intrinsic control depends on the control type; HTML intrinsic controls do not have a uniform set of properties, methods, and events. Each, however, does have a type property, which allows you to determine the type of control with which you are working.
The following sections will examine the HTML intrinsic controls and their most important properties, methods, and events.
8.3.3.1 The textbox control
The HTML textbox control is defined by the TYPE=Text> tag. Working with the textbox control is very straightforward, and closely resembles working with a Visual Basic TextBox control or a VBA UserForm TextBox control. The control's properties include the following:
Property |
Description |
---|---|
defaultValue |
The initial contents of the textbox, as defined by the VALUE attribute |
name |
The name assigned to the textbox by the NAME attribute |
type |
The type property of a textbox control is always "text" |
value |
The contents or text of the textbox |
The most useful methods of the textbox control (none of which take any parameters) are:
Method |
Description |
---|---|
Focus |
Moves the focus to the textbox control if it does not have the focus and fires its onFocus event |
Select |
Selects or highlights all of the text contained in the control |
Of the events supported by the textbox control, the following are most useful:
Event |
Description |
---|---|
onChange |
Fired when the contents of the textbox control have changed |
onFocus |
Fired when the control receives the input focus |
8.3.3.2 The checkbox control
The HTML Checkbox control is defined by the TYPE=checkbox> tag. Working with the Checkbox control is very straightforward, and closely resembles working with a Visual Basic checkbox control or a VBA UserForm checkbox control. The control's properties include the following:
Property |
Description |
---|---|
checked |
A Boolean that reflects whether the control is checked |
name |
The name assigned to the checkbox by the NAME attribute |
type |
The type property of a checkbox control is always "checkbox" |
The most useful methods of the checkbox control (none of which take any parameters) are:
Method |
Description |
---|---|
Click |
Simulates a click by causing the OnClick event to fire |
Focus |
Moves the focus to the textbox control if it does not have the focus and fires its onFocus event |
Of the events supported by the checkbox control, the following are most useful:
Event |
Description |
---|---|
onClick |
Fired when the user clicks on the checkbox |
onFocus |
Fired when the control receives the input focus |
onReadyStateChange |
Fired when the state of a checkbox has changed |
8.3.3.3 The radio button control
The HTML radio button control is defined by the TYPE=radio> tag. Because radio buttons reflect a set of two or more mutually exclusive choices, there is always more than one radio button with the same name on a form. The individual button's VALUE attribute determines which of those mutually exclusive choices the button represents, while the presence of the CHECKED attribute causes it to be the selected button of the set.
Since multiple radio buttons have the same name in the Elements collection, you cannot retrieve the selected radio button directly from the Elements collection. Instead, you must iterate the collection with the For Each...Next construct, extract the button whose Selected property is True, and retrieve its value. The code to do this looks something like the following:
Dim oElement, oElements, oRadio Dim sValue ' Get reference to Elements collection Set oElements = Document.frmTest.Elements ' Iterate collection looking for selected radio button For Each oElement in oElements If oElement.Type = "radio" And oElement.Checked Set oRadio = oElement Exit For End If Next ' Make sure a radio button was selected If Not oRadio Is Nothing Then sValue = oRadio.Value ' Perform any other processing End If
If the form has multiple sets of radio buttons, then you can look for the radio button of a particular name whose Checked property is True.
The radio button control's properties include the following:
Property |
Description |
---|---|
checked |
A Boolean that indicates whether the radio button is selected |
name |
The name assigned to the radio button by the NAME attribute |
type |
The type property of a radio button control is always "radio" |
value |
The option represented by this control in the set of radio button controls |
The most useful methods of the radio button control (none of which take any parameters) are:
Method |
Description |
---|---|
Click |
Simulates a click by causing the OnClick event to fire |
Focus |
Moves the focus to the textbox control if it does not have the focus and fires its onFocus event |
Of the events supported by the radio button control, the following are most useful:
Event |
Description |
---|---|
onClick |
Fired when the user clicks on a radio button |
onFocus |
Fired when the control receives the input focus |
onReadyStateChange |
Fired when the state of a radio button has changed |
8.3.3.4 The list box
A list box is defined by the ... tag, with its individual items defined by
tags. Depending on whether the MULTIPLE attribute is present, multiple items can be selected at a single time. Each item in the list box is a member of the Options collection, which is returned by the list box's Options property. In a single-selection list, you can determine the item selected by examining the SelectedIndex property. In a multiple-selection list, you can determine which items are selected by iterating the Options collection and checking whether the item's Selected property is True. If it is, you can retrieve the value of its Index and Text properties. The following code fragment illustrates this by forming strings containing the index numbers of selected items and the text of selected items:
Dim oElements, oDropDown, oOption Dim sSelected, sItems Set oElements = Document.frmTest.Elements Set oDropDown = oElements("lstColors") For each oOption in oDropDown.Options If oOption.Selected Then sSelected = sSelected & cStr(oOption.index) & vbCrLf sItems = sItems & oOption.Text & vbCrLf End If Next
The list box has the following properties:
Property |
Description |
---|---|
length |
The number of items in the list box. |
multiple |
A Boolean value that indicates whether multiple items can be selected at the same time. |
name |
The name of the drop-down list box, which corresponds to its NAME attribute. |
options |
A collection of Option objects, each of which represents an item in the list box. |
selectedIndex |
The index of the selected option. If the list box supports multiple selections, the selectedIndex property reflects the index of the first selected item in the list. |
type |
The type property of a drop-down list box is either "select-one" if the multiple property is False or "select-multiple" if the multiple property is True. |
The list box's most useful methods (none of which take any parameters) are:
Method |
Description |
---|---|
Click |
Simulates a click by causing the OnClick event to fire |
Focus |
Moves the focus to the textbox control if it does not have the focus and fires its onFocus event |
Of the events supported by the radio button control, the following are most useful:
Event |
Description |
---|---|
onChange |
Fired when a list box selection has changed |
onClick |
Fired when the user clicks on the list box |
onFocus |
Fired when the control receives the input focus |
onScroll |
Fired when the user scrolls the list box |
Individual Option objects, which represent individual items in the list box, have the following properties:
Property |
Description |
---|---|
index |
The ordinal position of the item in the Options collection. The first item is at position 0, and the last is at 1 less than the value of the list box's length property. |
selected |
A Boolean value that indicates whether the item is selected. For single-selection lists, only one item can return a True value for the selected property. |
text |
The text used to describe the item in the list box. |
8.3.3.5 Command button controls
HTML supports three types of buttons:
- The Submit button (defined with an TYPE=submit> tag), which submits form data to a web server
- The Reset button (defined with an TYPE=reset> tag), which resets form data to its default values
- A general-purpose command button (defined with an TYPE=button> tag), whose function is defined programatically
The three button types share a common set of properties and methods. The most commonly used properties are:
Property |
Description |
---|---|
name |
The name assigned to the button by the NAME attribute |
type |
The type property of a button control is defined by the TYPE attribute and is either "submit," "reset," or "button" |
value |
The button's caption |
The most commonly used methods are:
Method |
Description |
---|---|
Click |
Simulates a click by causing the OnClick event to fire |
Focus |
Moves the focus to the button if it does not have the focus and fires its onFocus event |
Finally, the most commonly used events are:
Event |
Description |
---|---|
onClick |
Fired when the user clicks on a command button. |
onFocus |
Fired when the control receives the input focus. |
onReset |
Fired when the Reset button is clicked and before existing form data is reset to its default values. This event handler is a function rather than a subroutine; by setting its return value to False, the reset operation can be cancelled. |
onSubmit |
Fired when the Submit button is clicked and before form data is submitted to the web server. This event handler is a function rather than a subroutine; by setting its return value to False, submission of form data to the server can be cancelled. |
8.3.4 The History Object
The History object represents the history list of recently opened documents. It has only one property, which is shown in Table 8-6, and three methods, which are listed in Table 8-7.
Property |
Description |
---|---|
length |
Returns the number of items in the history list |
Method |
Description |
---|---|
back |
Allows for bringing previously viewed document to be loaded into a target window or frame. Its syntax is History.back iDistance, where iDistance is the number of URLs to go back. |
forward |
Navigates to the next item in the history array. Its syntax is History.forward. |
go |
Navigates to a specific position in the history listing. Its syntax is History.go vLocation where vLocation can be an integer that indicates the relative position of the URL in the history list or a string that matches all or part of a URL contained in the browser's history. |
8.3.5 The Event Object
The Event object can be accessed inside of an event handler and provides additional information about that event. Its major properties are listed in Table 8-8.
Property |
Description |
---|---|
altKey |
A Boolean that indicates whether the Alt key was pressed when the event fired |
button |
For mouse events, indicates which mouse button set off the event |
ctrlKey |
A Boolean that indicates whether the Ctrl key was pressed when the event fired |
fromElement |
Returns a reference to the object where the cursor had just been prior to the onMouseOver or onMouseOut event |
keyCode |
The Unicode key value for the keyboard that triggered the onKeyUp, onKeyDown, and onKeyPress events |
reason |
Returns a code associated with the onDataSetComplete event signifying the state of a data transfer |
shiftKey |
A Boolean that indicates whether the Shift key was pressed when the event fired |
srcElement |
Returns a reference to the element object that fired the current event |
type |
Returns a string containing the name of the current event |
8.3.6 Using the Document Object Model
Let's take a look at a simple example, Example 8-10, and then build on that until we are exploiting a few of the different options available. It's not the most useful piece of code ever written, but it does demonstrate a piece of the Document Object Model hierarchy.
Example 8-10. A simple example using the Document Object Model
Demonstrates a simple use of the Document Object Model
First, we declare a variable called varTagName in the showme_onclick event procedure. We will set this variable equal to the value returned by the seventh member of the all collection, which corresponds to the seventh tag in the document. In this instance, this is the input button that we have created. When the user clicks the button, this page will generate a message box with the name of the tag. It is important to note here that tags are zero-based, so the first tag in the document will actually be tag 0. You can also refer to the tag by its name.
In Example 8-11, we are using the hierarchy to work into the individual elements of a table. First we reference the table by the tag name "table1," and then we can set the row and cell references after that. In this instance, we have given the table a tag name so that we can easily refer to it. If you do not give your tags names, then you must work with their index position on the page. If you look at the Name property of a tag with no name assigned, you will see the tag definition.
Example 8-11. Using client-side scripting to create a table
This is Cell One | This is Cell Two | This is Cell Three |
This is Cell One, Row Two | This is Cell Two, Row Two | This is Cell Three, Row Two |
The Document Object Model allows us to work with the individual elements on the page pretty effectively. You could apply this type of logic to make dynamic changes based on user interaction. This is the basis of Dynamic HTML (DHTML) coding. The Document Object Model is an active living concept, and there is currently an update to the standard being considered. The nice thing is that with each iteration of the standard, the DOM has become a more powerful tool for developers. For more information on DHTML, see Dynamic HTML: The Definitive Reference, Second Edition, by Danny Goodman (O'Reilly).
Chapter 9 Windows Script Components
|