Working with DHTML Object Model (I)
Contents
Working with Windows, Frames, and Dialogs
Using the Window Object
Creating and Using Frames
Creating and Using Modal Dialog Boxes
Showing a Help Window
Cross-Frame Scripting and Security
Dynamic Styles
Making Styles Dynamic
Dynamic Styles Are Easy
Documents Are Dynamic
Powerful Attributes
Special Considerations
Dynamic Styles Are Really Easy
The Document Is a Dynamic Thing
Some Powerful Attributes
Special Considerations
Changing Element Styles
Changing the Style of an IFRAME
Changing Element Classes
Scripting CSS Attributes
Managing Style Sheets
styleSheets Collection
Disabling Style Sheets
Replacing Style Sheets
Dynamically Changing Style Sheet Rules
User-Defined Style Sheets
Style Sheets and Printing
Setting Page Breaks For Printing
Examples
Example #1 -
Example #2 -
Example #3 -
Example #4 -
Example #5 -
Example #6 -
Example #7 -
Example #8 -
Example #9 -
Example #10 -
Example #11 -
Example #11 -
Example #12 -
Example #13 -
Example #14 -
Example #15 -
Example #16 -
Example #17 -
Example #18 -
Working with Windows, Frames, and Dialogs
Microsoft Internet Explorer creates a window object whenever it opens an HTML document. Because this object is the highest-level object in the object model, you use it to gain access to properties and sub-objects in the object model that you need to dynamically access the document content. The following topics explain how use the window object, create new window objects, and create special types of window objects.
Using the Window Object
The window object is the root of the object hierarchy. All properties in the object model are either accessed as properties of the window object or as properties of those properties. You can access the document through the document property of the window object. Properties that have properties are often called objects or sub-objects, so document is referred to as the document object.
Because the current window object is implied, you do not need to prefix the property with the window keyword. However, many people prefer to use the keyword to ensure that their scripts are as clear and readable as possible. For example:
status = "hello";
is the same as saying:
window.status = "hello";
and both will work when referring to the current window object.
Many of the properties of the window object can be used to carry out simple tasks, such as displaying messages, prompting for input, and loading new documents into the window. For example, you can display a simple modal message box from the current window by using the alert method and change the text in the Internet Explorer status bar by using the status property, as in the following example.
<HTML>
<HEAD><TITLE>A Simple Document</TITLE>
<SCRIPT LANGUAGE="JScript">
function doAlert()
</SCRIPT>
</HEAD>
<BODY onload="doAlert()">
<P>This is a very short document.
</BODY>
</HTML>
Example #1 -
You can use the navigate method or the location object to load a new document into a window. The action is similar to the user clicking a link to the new document, but can be carried out from script. The following example uses the navigate method to load the new document named "sample.htm" after a 60-second timer (using the setTimeout method) elapses.
window.setTimeout("window.navigate('sample.htm')", 60000);
You can also use the location object to navigate within the current document. For example, the following statement jumps to the anchor in the document having the name "sample".
window.location.hash="#sample";
There can be more than one window object at a time. For example, the browser creates one window object for each frame defined within a document. From the scripting perspective, the current window object is always the one that contains the document that contains the script. To access window objects other than the current window object, you precede the property with a window reference. The window.open method returns a reference to this new window that is then used in scripts to access properties and methods of the new window.
The following document uses the method to open a window and load the document "sample.htm" when the user clicks the button.
<HTML>
<HEAD><TITLE>Creating a Window</TITLE>
</HEAD>
<BODY>
<P><BUTTON onclick="window.open('sample.htm')">Open Sample</BUTTON>
</BODY>
</HTML>
Example #2 -
The new window is a separate instance of Internet Explorer, and the window object created for it is different than that of the original window. The new window can be referenced from the current window in script by the name "mysample". The following example creates a new window for the "sample.htm" document, then assigns the title of the new window's document to the status bar of the original window.
var new_window = window.open("sample.htm");
if (new_window != null)
window.status = new_window.document.title;
Once a window creates another, it can manage that window in a variety of ways, from loading new documents in the window with the navigate method or location object to closing the window with the close method. Closing the window unloads the document and closes the separate instance of Internet Explorer.
Because the user can also close the new window at any time, you should always make sure that the window exists before attempting to access it. You can do this by checking the closed property, which is set to true when the window is closed.
You can assign a name to a window when you create it by using the optional second parameter of the open method. The name is useful to use as the target of a link, causing the document specified by the link to be loaded in the window. The following document creates a window named "Sample". The links later in the document use "Sample" as the target name.
<HTML>
<HEAD><TITLE>Linking to Sample</TITLE>
</HEAD>
<BODY onload="window.open('sample.htm','Sample')">
<P>Click the following links to view the documents in the Sample window:
<P><A HREF="abc.htm" TARGET="Sample">All About Abc</A>
<P><A HREF="xyz.htm" TARGET="Sample">Some Words on Xyz</A>
</BODY>
</HTML>
Example #3 -
By default, the open method creates a window that has a default width and height and the standard menu, toolbar, and other features of Internet Explorer. You can alter this set of features by using the optional third parameter. This parameter is a string consisting of one or more feature settings, including settings for the position and dimension of the window. For example, the following creates a window that is 200-by-400 pixels, has a status bar, but does not have a toolbar, menu bar, or address field.
window.open("sample.htm",null,
"height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
Creating and Using Frames
Frames are a way to organize and structure HTML documents, creating compound views that the user sees within the main window of Internet Explorer. Because each frame is itself a unique window within the main window, you use the window object to access the frame's content.
You create frames by using the IFRAME element or FRAMESET and FRAME elements. Each element creates a frame and loads a specified document. For example, the following document creates two equally sized rectangular frames that fill the main window.
<HTML>
<HEAD><TITLE>Two Equal Frames</TITLE>
</HEAD>
<FRAMESET COLS="50%,*">
<FRAME SRC=x.htm>
<FRAME SRC=y.htm>
</FRAMESET>
</HTML>
Example #4 -
In a document within a frame, such as the "x.htm" and "y.htm" documents in the example above, you can use the window object as you would in a document within the main window. This means you can get access to the document and event objects for the frameset document and write script that will run from this frameset document. Note that if you use script, or need to instantiate an OBJECT from this frameset document, you need to define these in the HEAD section. Also note that a BODY element is mutually exclusive from a FRAMESET. Using both in a single document will result in the first one being instantiated and the second one ignored. Many authors try to use a BODY element to set the background color, and then instantiate a FRAMESET. Internet Explorer 4.0 will instantiate the BODY, and ignore the FRAMESET. Move the background color settings to the FRAMESET, and remove the BODY from this document, and the browser will intantiate the FRAMESET as you would expect.
You can also gain access to the window that created the frame (called the parent window) and to the other frames created by the parent by using the parent property and the frames collection. The following JScript example using these to display the URL of the documents in each frame.
for (i=0; i<window.parent.frames.length; i++)
alert("Frame #" + i + " contains: " + window.parent.frames(i).location);
The frames collection contains window objects for each frame, so you can use the same properties and methods with these objects as you would within the current window. For example, you can gain access to the complete contents of the document in another frame by using frames, as in the following example, to display the title of each document.
for (i=0; i<window.parent.frames.length; i++)
alert("The title of frame #" + i + " is: " + window.parent.frames(i).document.title);
Note Cross-frame security limits scripting to documents loaded from the same domain. Use the domain property to determine and/or set the domain of a document.
The frames collection also works this way for the document object. In this case, the frames collection from the document contains window objects for all frames created by IFRAME elements in a document. Consider the following document.
<HTML>
<HEAD><TITLE>Two Floating Frames</TITLE>
<SCRIPT>
function showFrames()
</SCRIPT>
</HEAD>
<BODY onload="showFrames()">
<IFRAME SRC="x.htm" ALIGN=LEFT></IFRAME> Here's some text to the right of a frame.
<BR CLEAR=LEFT>Here's some text beneath the frame.
<BR>
<IFRAME SRC="y.htm" ALIGN=RIGHT></IFRAME> Here's some text to the left of a frame.
<BR CLEAR=RIGHT>Here's some text beneath the frame.
</BODY>
</HTML>
Example #5 -
The document above contains two floating frames, one aligned to the left and the other to the right. Once the document is loaded, the "showFrames" function uses the frames collection to access each frame and display the title of the corresponding document.
Unlike windows created using the open method, you cannot close the window associated with a frame. The frame is "closed" when the window that created it is unloaded. Also, properties that apply to the main window, such as status, have no purpose within a frame. Frames do not have status bars, so attempting to get or set status has no effect for the individual frames, and you should access the parent frameset document to set the status bar.
Notice that accessing the window object associated with a frame is not the same as accessing the FRAME or IFRAME element that created the frame. In particular, you cannot access the attributes of these elements by using the window object. Instead, you must use the object for the element, which you can get from the all collection for the document that contains the frame element. For example, if you want to remove the scroll bars from a frame, you have to set the scrolling property of the IFRAME element as follows:
document.all.tags("IFRAME").item(1).scrolling="no";
Creating and Using Modal Dialog Boxes
A dialog box is a special window that you create by using the showModalDialog method on the window object. Dialog boxes are useful for soliciting input from the user in a way that does not obscure the information in the current window. They are also useful for displaying important information that the user should act upon or acknowledge before proceeding.
The showModalDialog method is similar to the open method in that it takes the URL of an HTML document and displays the document in a new window. One of the main differences, however, is that the dialog box is modal, meaning it does not release the input focus until it is closed. This means the user cannot switch back to the window that created the dialog box until she closes the dialog box. However, this does not prevent the user from switching to other windows or applications.
You typically create dialog boxes in response to user input, such as clicking a button or choosing an item in a menu. The following example calls showModalDialog directly from the onclick attribute of a BUTTON element.
<BUTTON onclick="window.showModalDialog('dialog.htm')">Search</BUTTON>
The method in the example above creates a dialog box having the standard dialog box size and features, and loads the document "dialog.htm" into the new window.
You can load any valid HTML document into a dialog box, but most dialog documents contain one or more controls with which the user supplies input or directs an action. For example, the following document provides a text control for letting the user specify a string to search for and buttons to confirm or cancel the search. Notice that the string is returned to the main window by assigning it to "returnValue".
<HTML>
<HEAD><TITLE>Search For</TITLE>
<SCRIPT LANGUAGE="JScript">
function doOK()
function doCancel()
</SCRIPT>
</HEAD>
<BODY>
<P><B>Search For:</B> <INPUT ID=MySearch TYPE=text>
<CENTER>
<BUTTON onclick="doOK()">OK</BUTTON>
<BUTTON onclick="doCancel()">Cancel</BUTTON>
</CENTER>
</BODY>
</HTML>
Example #6 -
When the document above is displayed, the user can type a string into the text control (identified by "MySearch") and click either the OK or Cancel button to carry out an action. Clicking OK calls the "doOK" function, which retrieves the text from the text control and assigns it to the returnValue property of the dialog box. Clicking Cancel calls "doCancel", which assigns an empty string to this property. Both functions then call the close method to close the dialog box and return the input focus to the original window.
The returnValue property on the window object specifies the value to be returned by the showModalDialog method after the dialog box closes. Setting this property is one way a dialog box can return information to the original window. Assuming the document in the previous example is in a file named "search.htm", the following example can use the returned string to carry out a search.
function doSearch()
You can pass arguments to a dialog box by using the second parameter of showModalDialog. This parameter accepts any valid type, so an array can be passed just as easily as a discrete type.
var aCafeArgs = new Array("Tall", "Decaf", "Non-fat", "Mocha");
var cResult = window.showModalDialog("barista.htm", aCafeArgs);
A dialog box can retrieve the arguments through the dialogArguments property of the window object. Passing arguments is a useful way for the original window to specify the initial values for the controls in the dialog box. For example, consider the dialog document in the search example. By scripting the onload event of the BODY element to call the following function, the dialog can set the initial search string to a value supplied by the original window.
function doInit()
.
.
.
<BODY onload="doInit()">
To set the initial search string to the words "Sample Text", the original window calls showModalDialog as in the following example.
var str = showModalDialog("search.htm", "Sample Text");
A better way to make use of the dialog arguments for this document is to store the search string in a variable within the document of the original window, as in the following example.
var str = "";
function doSearch()
Storing the returned string in the global variable ensures that the previous search string is available whenever the user requests another search. Remember that stored values are discarded when a document is unloaded, so you cannot store the previous string with the dialog document. This also means that the stored string in the original window is discarded when that document is unloaded.
In addition to setting initial values, you can also set the input focus to a specific control in the dialog box by using the focus method. This ensures that when the dialog document is loaded, the user can begin entering input immediately without first moving the focus to an appropriate control. The input focus is typically set in the same function that sets initial values for the dialog box. To set the focus to the text control in the previous example, use the following:
window.document.all.MySearch.focus();
If the original window has more that one value to exchange with the dialog box, it can do this by passing an object to the dialog as an argument. For example, the following dialog document prompts the user with both a "Match Case " check box and a "Search For" string. To receive the user's settings for these, the original window passes an object that the dialog sets when the user presses OK or Cancel.
<HTML>
<HEAD><TITLE>Search For</TITLE>
<SCRIPT LANGUAGE="JScript">
function doInit()
window.document.all.MySearch.focus();
window.returnValue = false;
}
function doOK()
window.close();
}
function doCancel()
</SCRIPT>
</HEAD>
<BODY onload="doInit()">
<INPUT ID=MatchCase TYPE=checkbox> <B>Match Case</B>
<P><B>Search For:</B> <INPUT ID=MySearch TYPE=text>
<CENTER>
<BUTTON onclick="doOK()">OK</BUTTON>
<BUTTON onclick="doCancel()">Cancel</BUTTON>
</CENTER>
</BODY>
</HTML>
Example #7 -
Be careful! Any document that uses this dialog document needs to properly declare and initialize the object. The following example declares the "myDialog" object and initializes the object before calling showModalDialog.
function myDialog()
function doSearch()
An alternate way to pass multiple values between the original window and the dialog box is to concatenate those values into a single string, and leave it to the documents to parse the string and extract the values.
The appearance and size of a dialog box can be set from the third parameter of the showModalDialog method. The following example creates a dialog box that uses a default font size of 10 pixels and a dialog width and height of 10 ems.
window.showModalDialog("dialog.htm",null,
"font-size:10px;dialogWidth:10em;dialogHeight:10em")
As you can see in the example above, the third parameter takes a string, consisting of one or more settings separated by semicolons (;). Each setting consists of a name and a value separated by a colon (:) or equal sign (=). The value depends on the ornament. If it is a number, it takes a units designator, such as "px" or "em".
You use the dialogWidth and dialogHeight names to set the initial width and height of the dialog box. Similarly, you can use dialogLeft and dialogTop to set the initial position of the dialog box relative to the upper-left corner of the desktop (not the parent window). If you don't want to calculate the left and top positions for the dialog box, you can center it in the desktop by using the center keyword.
Although the position, width, and height of a dialog box are typically set by the parent document, you can retrieve and change these settings from within the dialog box itself by using the dialogLeft, dialogTop, dialogWidth, and dialogHeight properties. Changing these settings is important, for example, if you want to expand the content of the dialog box to show additional options that the user can choose from.
You can set the default typeface, font size, weight, and style for text in the dialog box by using the font, font-size, font-weight, and font-style names. These take the same values as the CSS attributes of the same name. The default settings apply only to text in the dialog box that does not already have explicit font settings.
Showing a Help Window
You can show help files in the browser using the showHelp method on the window object. The following example creates a help window that would display an HTML help file. For HTMLHelp, there are no modifying parameters, and only defaults will apply to the new window.
<BUTTON onclick="window.showHelp('helpinfo.htm')">Show Help</BUTTON>
The showHelp method can also be used to display WinHelp files. To display WinHelp files, the first parameter of the method specifies an .hlp file, the second parameter specifies a context identifier, and the third (optional) parameter can be used to specify "popup". The default view for help files is to show the help file in the main browser window. If "popup" is specified for WinHelp files, the help file is displayed in a separate window.
Cross-Frame Scripting and Security
With Dynamic HTML, content in different windows and frames can interact in powerful ways by scripting with the object model. However, since it is possible for a browser to simultaneously display unrelated documents in its various windows and frames, certain rules must be enforced to protect data integrity and privacy of information.
This section describes how and why these restrictions apply in the DHTML object model. All rules about script interaction apply equally to windows, dialog boxes, FRAMESETs, FRAMEs, and IFRAMEs.
For most content, only interactions with content from the same domain are allowed. For example, a typical page on https://www.microsoft.com/ can freely script content on any other page on https://www.microsoft.com/ but cannot script to pages that are located on a different Web domain. The DHTML object model uses the document.domain property to enforce this restriction: only pages with identical domain properties are allowed free interaction. The protocol of the URL must also match. For instance, an HTTP page cannot access HTTPS content.
The range of permissible access for a page can be expanded when a script assigns the document.domain property to a suffix of the site name space, up to the second-level domain. For example, a page on https://www.microsoft.com/ can assign the document.domain property-initially "www.microsoft.com"-to be "microsoft.com" to broaden access to include pages in https://home.microsoft.com or any other site, as long as the other pages also set the document.domain property to the identical value. Since only pages from a site whose name ends with "microsoft.com" will permit this domain to be set, it is assured that content from the same provider mutually agrees to interact and is free to do so. Domain suffixes shorter than the second-level domain (such as just "com") are disallowed because they expose beyond a single provider. For international site names such as https://www.microsoft.co.jp/, the second-level domain for widest access would be "microsoft.co.jp" (not "co.jp").
Since it is important to be able to navigate windows or frames to any URL beyond the domain restriction, these types of accesses are always permitted. Only access that attempts to read-out or modify content is restricted. For instance, the window.location might be assigned to cause navigation to occur, but this property cannot be read if the URL is of a different domain. This would allow one page to learn where the user has been browsing, and to allow this is a breach of the user's privacy.
Some restrictions that apply to pages of different domains include:
window.location |
Property can be set to navigate, but cannot read. |
Other location |
Functionality is blocked. |
document.href |
Property can be set to navigate but cannot read. |
Other document |
Functionality is blocked. |
<IFRAME> |
src property can be set to navigate but cannot read |
Scripts that attempt to access parts of the object model to which they do not have access will be blocked with a "permission denied" error. While domain security can prevent certain types of content interaction, it is important to understand that this restriction is necessary to ensure security. For example, without domain security, a rogue page could "snoop" on other pages or, using DHTML, manipulate its content.
Dynamic Styles
You can dynamically change the style of any HTML element in a document. You can change colors, typefaces, spacing, indentation, position, and even the visibility of text. Because the Dynamic HTML object model makes every HTML element and attribute accessible, it is easy to use scripts to dynamically read and change styles. The following section describes dynamic styles and provides a general explanation of how to use the object model to examine and modify styles.
Making Styles Dynamic
Web authors gained unprecedented control over the look of documents with the introduction of cascading style sheets (CSS) in Internet Explorer 3.0. CSS allows authors and readers to attach a style to Web pages that defines the presentation of content by modifying style attributes of corresponding HTML elements.
Microsoft Internet Explorer 4.0 takes CSS technology a step further, providing the ability to dynamically change any HTML attribute, at any time, on any element. Using simple JavaScript, JScript, or VBScript the attributes for any HTML element can be modified in response to any document or user event, and the page will automatically reflow without reloading the page from the server. This means that, for example, the STYLE element can be changed to change an element's inline CSS style, or any other HTML attribute (such as the SRC attribute on an IMG element).
Dynamic Styles Are Easy
You might expect that this new functionality will require that you learn a new set of HTML tags. However, dynamic styles have been designed to require no new HTML. CSS attributes can be set from the style sub-object for each element, while regular HTML attributes are accessed as properties on each element. For instance, to change the color of text within an H1 heading to red when the user moves the mouse over the heading, all you need to add is a simple piece of code known as an event handler.
<H1 onmouseover="this.style.color = 'red';">Make me red</H1>
The event handler, onmouseover="this.style.color = 'red';" takes a predefined action (onmouseover) and assigns an action for it to carry out when it fires (this.style.color = 'red'). It is just as easy to change not only the style but the content of a SRC attribute in the same manner.
<IMG src="before.gif" onmouseover="this.src = 'after.gif';">
In this example, as the mouse moves over the image, its source changes from "before.gif" to "after.gif".
Documents Are Dynamic
When the color of an element is changed dynamically, it still fits into the same physical space in the document as it did before the color change. This is a relatively simple task for the browser to carry out. However, there are other styles, such as fontSize or fontFamily, that, when changed, actually change the size of the element and the amount of space required to display that element in the document. Internet Explorer 4.0 handles each such change automatically by reflowing a document to ensure that all the elements fit perfectly without reloading the document from the server.
<html>
<body>
This is some text.
<span style="color:blue" onclick="this.style.fontSize = '30'">
This is more text.</span>
This is even more text.
</body>
</html>
Example #8 -
Initially, the document has two lines of text, identical in font size and color. After clicking "This is more text," the text changes, increasing in size and changing to blue. The browser automatically adjusts the line spacing to accommodate the new text size.
Powerful Attributes
Because Internet Explorer 4.0 automatically reflows the document when attribute values change, some very powerful functionality can be built with very small amounts of code. For example, using the CSS display attribute, you can make elements on the page disappear, and treat them as if they were never on the page in the first place.
<html>
<body>
<div style="cursor: hand" onclick="toggle(document.all.HideShow);">
Click Here</div>
<span style="color: blue" id=HideShow>This will go away</span><br>
This is some text
<script>
function toggle(e) else
}
</script>
</body>
</html>
Example #9 -
This HTML displays three lines. When the user clicks the line that says "Click Here", the browser changes the display attribute of the SPAN element with the text "This will go away" to display: none, and the text beneath shifts up to occupy its space. When clicked again, the display attribute is reset so that the "Click Here" text is visible again.
Notice that by simply setting display: none on an element, it disappears and the browser automatically reclaims the space it occupied. This mechanism can be used to create pages that display new information, such as an expandable table of contents, as the user interacts with individual entries. The two supported values for the display property are none and "" (or null).
The sample above also makes use of the CSS cursor attribute. The cursor attribute allows a Web author to specify what the cursor will look like when it is over an element. In this case, the hand cursor was chosen to indicate that the text titled "Click Here" would perform an action when clicked, just like a text link on a Web page. Using the cursor attribute eliminates the need to use an anchor tag to have the cursor change to a hand, indicating the contents are "clickable".
The set of valid values for the cursor attribute are crosshair, default, hand, move, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize, text, wait, and help.
While the display property makes an element invisible and allows the browser to reclaim the space that it occupied, the visibility property can be used to simply make an element disappear, but still reserve its space in the document.
The following example is identical to the previous demonstration, except it uses the visibility property instead of the display property.
<html>
<body>
<div style="cursor: hand" onclick="toggle(document.all.HideShow);">
Click Here</div>
<span style="color: blue" id=HideShow>This will go away</span><br>
This is some text
<script>
function toggle(e) else
}
</script>
</body>
</html>
Example #10 -
Notice how in this example the line of text will become invisible, but the content below does not shift up to reclaim its space.
Special Considerations
You might have noticed that many CSS properties have a dash in their name (such as background-color). The dash, as you may know, isn't a valid character for identifiers in most scripting languages. To get around this little problem, continue to use the dashed name when specifying the CSS attribute in HTML or in a style sheet, but when accessing the attribute as a script property, remove the dash, and capitalize the next letter. For example:
background-color becomes backgroundColor
border-left becomes borderLeft
margin-bottom becomes marginBottom
The CSS attribute names specified in the HTML or style sheet are listed in the CSS Attributes section of the SDK. The corresponding scriptable properties are listed as properties of the style object in the Objects section of the SDK.
Also notice that while any CSS property can be set at any time, the current settings on the STYLE element will only reflect its inline styles, and not any inherited styles that are defined in a global style sheet with a STYLE or LINK tag. The following example shows what happens when a style is defined both globally and inline.
<html>
<head>
<style>
.class1
</style>
</head>
<body>
<div id=SetByClass class=Class1>Set By Class</div>
<div style="font-family: arial">
<div id=Inherited>Inherited</div>
</div>
<div id=DirectlySet style="font-family: arial">Directly Set</div>
<div id=SetWithScript>Set with Script</div>
<script>
alert(SetByClass.style.fontFamily);
alert(Inherited.style.fontFamily);
alert(DirectlySet.style.fontFamily);
SetWithScript.style.fontFamily = "arial";
alert(SetWithScript.style.fontFamily);
</script>
</body>
</html>
Example #11 -
When this document loads, four alert dialog boxes pop up successively. The first two are blank, while the next two contain the text "arial." While all the text on the document is Arial, referencing style.fontFamily will show "arial" only on the DIV that had the font-family property set with an inline style or was previously set with script.
Dynamic Styles Are Really Easy
You might be asking: "OK, what new HTML tags do I need to use this Dynamic Styles stuff?" Answer: "None." In this example, as the mouse moves over the H1 heading, the color changes to red:
<H1 onmouseover="this.style.color = 'red';">Make me red</H1>
In this example, as the mouse moves over the image, its source changes from before.gif to after.gif:
<IMG src="before.gif" onmouseover="this.src = 'after.gif';">
Regular HTML attributes are accessed as properties on each element. CSS attributes can be set from the style sub-object.
The Document Is a Dynamic Thing
When the color of an element is changed dynamically, it still fits into the same space as it did before the color changed. This is a relatively basic operation. However, there are other styles, such as fontSize or fontFamily, which, when changed, actually change the size of the element. Internet Explorer 4.0 handles each such change automatically for you. It will automatically re-flow a document to ensure that all the elements fit perfectly. For example:
<html>
<body>
This is some text.
<span style="color: blue" onclick="
this.style.fontSize = '30'">This is more text.</span>
This is even more text.
</body>
</html>
Example #11 -
Some Powerful Attributes
Because Internet Explorer 4.0 automatically re-flows the document when attribute values change, some very powerful functionality can be built with very small amounts of code. For example, using the display attribute, you can make elements on the page disappear, and treat them as if they were never on the page.
For example:
<html>
<body>
<div style="cursor: hand" onclick="toggle(document.all.HideShow);">
Click Here</div>
<span style="color: blue" id=HideShow>This will go away</span><br>
This is some text
<script>
function toggle(e) else
}
</script>
</body>
</html>
Example #12 -
This HTML displays three lines. When the user clicks on the line "Click Here," the SPAN with the text "This will go away" will be set to display: none. When clicked again, it will be reset.
Notice that simply by setting display: none on an element, it disappears, and the browser automatically reclaims the space it occupied. This mechanism can be used to have pages that display new types of information on demand, without having to revisit the server. The two supported values for the display property are none and "" (or null).
This sample also makes use of the cursor CSS attribute. The cursor attribute allows a Web author to specify what cursor will be shown when it is over an element. In this case, we chose the hand cursor to indicate that the text titled "Click Here" would perform an action when clicked. The use of the cursor attribute obviates the need to wrap elements in an anchor in order to have the cursor change to a hand, an effect you would use to indicate that something will happen if the user clicks.
The set of valid values for the cursor property are: crosshair, default, hand, move, e-resize, ne-resize, nw-resize, n-resize, se-resize, sw-resize, s-resize, w-resize, text, wait, and help.
While the display property makes an element invisible, and allows the browser to reclaim the space that it occupied, the visibility property can be used to simply make an element disappear, but still reserve its space in the document.
The following example is identical to the above example, except it uses the visibility property instead of the display property.
<html>
<body>
<div style="cursor: hand" onclick="toggle(document.all.HideShow);">
Click Here</div>
<span style="color: blue" id=HideShow>This will go away</span><br>
This is some text
<script>
function toggle(e) else
}
</script>
</body>
</html>
Example #13 -
Watch in this example how the line will become invisible, but its space will not be reclaimed.
Special Considerations
You might have noticed that many CSS properties have a dash in their name (such as background-color). The dash, as you may know, isn't a valid character for identifiers in most scripting languages. To get around this little problem, continue to use the dashed name when specifying the CSS attribute in HTML or in a style sheet, but when accessing it in a script, remove the dash, and capitalize the next letter. For example:
background-color becomes backgroundColor
border-left becomes borderLeft
margin-bottom becomes marginBottom
Also notice that while any CSS property can be set at any time, using the current settings on the STYLE object will only indicate its inline styles, and not any inherited styles or styles obtained by setting the class of an element.
For example:
<html>
<head>
<style>
.class1
</style>
</head>
<body>
<div id=SetByClass class=Class1>Set By Class</div>
<div style="font-family: arial">
<div id=Inherited>Inherited</div>
</div>
<div id=DirectlySet style="font-family: arial">Directly Set</div>
<div id=SetWithScript>Set with Script</div>
<script>
alert(SetByClass.style.fontFamily);
alert(Inherited.style.fontFamily);
alert(DirectlySet.style.fontFamily);
SetWithScript.style.fontFamily = "arial";
alert(SetWithScript.style.fontFamily);
</script>
</body>
</html>
Example #14 -
When this document loads, four alert dialogs will pop up successively. The first two will be blank, while the next two will contain the text "arial." While all of the text on the document is Arial, referencing style.fontFamily will show "arial" only on the DIV that had the font-family property set with an inline style or was previously set with script.
Changing Element Styles
Dynamic HTML allows you to write script that can change the HTML attributes that modify a given element. These attributes can be things such as the SRC attribute on an IMG or IFRAME element, or the STYLE attribute for a DIV element. This document shows you how to change the SRC= attribute on an IFRAME element so that the contents of IFRAME change on the fly. The same example also shows you how to change the background color of the body for the SRC= document of the IFRAME. The next set of examples shows how to change the class name of the element so that it is associated with a different style sheet.
Dynamic HTML gives you scriptable access to all HTML elements, attributes, and CSS styles. You as the author can use these techniques to design some pretty cool DHTML Web pages.
Changing the Style of an IFRAME
The following example shows how to change the contents of IFRAME as well as change the style attribute of the BODY element of the contained IFRAME. Click the Show Me button to show the page, and then look at the code.
<HTML>
<HEAD><TITLE>Changing Element Attributes</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function change_image()
function change_background()
</SCRIPT>
</HEAD>
<BODY>
<IFRAME id=myiframe src="frame_content.htm">
</IFRAME>
<BUTTON onclick=change_image()>Change contents of the IFRAME</BUTTON>
<BUTTON onclick=change_background()>Change the background color of the IFRAME</BUTTON>
</BODY>
</HTML>
Example #15 -
Changing Element Classes
There are two primary ways to change the inline style for an element-either change the element's STYLE attribute, or change the className of the element to match a defined class in a global style sheet. The following example shows how straightforward it is to change the inline STYLE attribute with an event.
<H1 id=myStyle onclick="this.style.color=blue">This text will change to blue when clicked </H1>
This changes the property "color" of the style sub-object for the H1 element.
However, to change the style for more than one element, use global style sheets, which let you define styles based on a "contextual selector"-styles can apply to tag names, element identifiers, or all elements in a class. The DHTML class attribute on every element lets you associate any element with any class name. This way, multiple elements can belong to a single class, and setting a global style for a class means that the style sheet applies to every element with that class name.
Because the class attribute can be scripted, you can dynamically change class associations with elements in a document, as in the following example.
<HTML>
<HEAD><TITLE>Changing Element Attributes</TITLE>
<STYLE>
.textRed
.textBlue
</STYLE>
</HEAD>
<BODY>
<H1 class=textBlue onmouseover="this.className='textRed'" onmouseout="this.className='textBlue'">Mouse over this text to see
the color change from blue to red and back to blue</H1>
</BODY>
</HTML>
Example #16 -
In the example, global rules are defined for two classes, "textRed" and "textBlue". The H1 initially is a part of the textBlue class and therefore is displayed in blue. Moving the mouse over the text fires the onmouseover event, and the inline event handler changes the association of the H1 element to the textRed class, which renders the text red. Note that the class attribute is referenced through the className property.
Note The scriptable properties for CSS styles are all read/write except position. You cannot dynamically set a nonpositioned element to be positioned. If you want to absolutely position an element using an event handler script, be sure that the element has its initial position set to relative using either a global style sheet or an inline style.
Scripting CSS Attributes
All style attributes are strings. Several properties have been added to the style object to help manipulate values as nonstrings. For example, pixelHeight is an integer so that the height of an object can be mathematically manipulated in base pixel units regardless of how the height attribute was set. The posHeight property is an integer that describes the height attribute in the units to which the author originally set the CSS height attribute.
If a style property represents some number of units, you can include a units designator when assigning the value. The "pt" (points) and "px" (pixels) designators are used in the following examples.
document.all.MyElement.style.fontSize = "24pt";
document.all.MyElement.style.fontSize = "120px";
If you don't supply a units designator, the default unit of measure for the property is used. One benefit of this is that you can assign a number or the result of an expression (rather than a string) and it will be converted automatically. For example, the assignments below are the same-they both set the font size to 72 pixels.
document.all.MyElement.style.fontSize = "72";
document.all.MyElement.style.fontSize = 72;
Managing Style Sheets
Dynamically changing cascading style sheet (CSS) styles that are applied to documents is not limited to the inline styles (styles defined with the STYLE= attribute). Global style sheets defined with a LINK or STYLE tag in the HEAD section of the document can be manipulated through script. Manipulating the global style sheet is a powerful way to dynamically change the styles that apply to Web pages.
styleSheets Collection
Global style sheets are made accessible to script through the styleSheets collection on the document object. This collection represents instances of STYLE and LINK elements in the HEAD section of the document with a type (or type attribute) of "text/css". Style sheets of other types are not supported. Imported style sheets are contained within a STYLE element, and are surfaced by the containing STYLE element as type styleSheet. STYLE and LINK elements can be added to the document through the createElement method on the window object. This method adds a new style sheet object to the styleSheets collection on the document. Style rules and imported style sheets can then be added to this style sheet with the addImport and addRule methods.
You can use identifiers to access style sheets in the document. You set an identifier for a style sheet by setting the ID attribute of the LINK or STYLE element.
Disabling Style Sheets
A powerful feature of the styleSheet object is that you can turn a style sheet off and on dynamically. The disabled property defaults to false, but can be set to "true" to remove the style sheet from being applied to the document. Toggling the application of style sheets is another technique for dynamically changing the style of a Web page.
Replacing Style Sheets
You can replace one style sheet with another by setting the href property of the style sheet to the URL of the replacement, as in the following example:
if (document.styleSheets(0).href != null)
document.styleSheets(0).href = "newstyle.css";
When you replace a style sheet, the styleSheets collection is immediately updated to reflect the change. Replacing a style sheet in this way is available only for style sheets that have been included using the LINK element or the @import statement. The href property is null for style sheets defined using the STYLE element.
Dynamically Changing Style Sheet Rules
Each style sheet is a collection of rules. The rules collection of the styleSheet object enumerates these rules. This collection can be accessed even if the style sheet is disabled. Rules are added and removed from the rules collection with add and remove methods on the individual style sheet. A rule that is added to a disabled style sheet will not apply to the document unless the style sheet's disabled property is changed to "false".
The rules in the rules collection are in the source order of the document. Style rules linked in using the "@import" syntax of CSS are expanded in-place in the rules collection per the CSS1 specification.
As rules are added or deleted, a rule's absolute position in the rule collection may change, but its position relative to other rules will remain the same. The default location to add a new rule (without specifying an index) is at the end of the collection, which is the highest precedence (not accounting for selector specificity, as per the CSS specification) and is applied to the document last. If an index is supplied, the rule should be inserted before the rule currently in that ordinal position in the collection, or, if the index is larger than the number of rules in the collection, it should be added to the end .
The following is an example of using the addRule method.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JScript">
function newRule()
</SCRIPT>
<STYLE ID="MyStyles">
H1
H2
</STYLE>
</HEAD>
<BODY onclick="newRule()">
<H1>Welcome!</H1>
<P>This document uses style sheets.</P>
<H2>Ways to Include Style Sheets</H2>
<UL>
<LI>LINK
<LI>STYLE
<LI>@import
</UL>
</BODY>
</HTML>
Example #17 -
Each rule has a selector, identifying the elements to apply the rule to, and a list of style assignments, identifying the style attributes to apply to these elements. The selector is typically the name of an element, class, or identifier, but can also be a combination of names, such as a comma-separated list of element names. Each style assignment consists of a style attribute name and a value separated by a colon. If there is more than one assignment, the assignments are separated by semicolons. The rule object has a readOnly property that indicates whether the particular rule is from an editable source. Imported and linked styles cannot be edited, so the readOnly property for the contained rule would return "true".
As an example of manipulating style rules, consider the following simple style sheet:
<STYLE
ID="MyStyles">
H1
H2
</STYLE>
The rules collection would contain two rules. Each rule has two parts (and corresponding properties): the selector and the style. The selector in the first rule in the above style sheet is "H1".
alert(document.styleSheets[0].rules[0].selectorText); // this returns "H1"
To change the style of the first rule in the first style sheet, use the following:
document.styleSheets[0].rules[0].style.color = "blue";
User-Defined Style Sheets
Through the Options dialog box of the browser, users can specify a style sheet that they want to have applied to all pages that they view. This style sheet will be applied to the document first, meaning the author has the final say of how a CSS attribute is defined. Style sheets defined in the document override the user-defined style sheet. The user-defined style sheet is simply a "preference" that will affect the page if the author has not defined a rule for that CSS attribute. User-defined style sheets specified by the user in the Options box dialog of the browser are not listed in the styleSheets collection.
Style Sheets and Printing
The STYLE and LINK elements support the MEDIA attribute, which defines the output device for the style sheet. Values for MEDIA are SCREEN, PRINT and ALL. The default is SCREEN, so not setting the MEDIA attribute causes the style sheet to always be applied to the page for the screen as well as printing. The PRINT value specifies that the style sheet is used when the page is printed; this value does not affect how the document will be displayed onscreen. The ALL value determines that the document is formatted for both the screen and print.
Note that all filter: styles, including visual effects filters, are ignored when printing. Internet Explorer renders this content for printing with any applicable text style properties.
Setting Page Breaks For Printing
You can control the placement of page breaks in your documents by using the page-break-before and page-break-after attributes. These attributes indicate when to break to a new page when printing the document and on what page (left or right) to resume printing. These attributes are useful when you want to print long documents into logical sections.
For example, the following document defines a class "page" in a style sheet and uses it to set page breaks in the document.
<HTML>
<HEAD><TITLE>Dynamic Styles: Page Breaking</TITLE>
<STYLE>
BR.page
</STYLE>
</HEAD>
<BODY>
. content on page 1 .
<BR CLASS=page>
. content on page 2 .
</BODY>
</HTML>
Example #18 -
You can set page breaks from within a script by setting the pageBreakBefore and pageBreakAfter properties on the style object. The following example sets a page break immediately before each H1 element in the document. The heading is subsequently printed on a right-hand page.
var coll = document.all.tags("H1");
for (i=0; i<coll.length; i++)
|