Contents Index Topic Contents | ||
Previous Topic: Document Object Model Next Topic: Scripting with Elements and Collections |
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.
Be sure to review Cross-Frame Scripting and Security for cross-window and frame scripting issues. Security considerations limit the cross-window access from scripts, and reading this section will help you understand what you can and cannot do through scripting.
Creating and Using Modal Dialog Boxes
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. For example, you 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. For a complete list of properties of the window object, see Properties.
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() { window.status = "Page is loaded!"; alert("Page is loaded!"); } </SCRIPT> </HEAD> <BODY onload="doAlert()"> <P>This is a very short document. </BODY> </HTML>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>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>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");For more information about the window features, see open.
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>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. See Cross-Frame Scripting and Security for more information on cross frame security and scripting considerations.
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() { for (i=0; i<window.document.frames.length; i++) alert("The title of frame #" + i + " is: " + window.document.frames(i).document.title); } </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>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";For more information about element objects and their properties, see Scripting with Elements and Collections.
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() { window.returnValue = window.document.all.MySearch.value; window.close(); } function doCancel() { window.returnValue = ""; window.close(); } </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>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() { var str = showModalDialog("search.htm"); if (str == "") return; // user canceled search else { // search for the string } }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() { if (window.dialogArguments != null) window.document.all.MySearch.value = window.dialogArguments; } . . . <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() { str = showModalDialog("search.htm", str); if (str == "") return; // user canceled search else { // search for the string } }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() { if (window.dialogArguments != null) { window.document.all.MySearch.value = window.dialogArguments.str; window.document.all.MatchCase.checked = window.dialogArguments.caseSensitive; } window.document.all.MySearch.focus(); window.returnValue = false; } function doOK() { window.returnValue = true; if (window.dialogArguments != null) { window.dialogArguments.str = window.document.all.MySearch.value; window.dialogArguments.caseSensitive = window.document.all.MatchCase.checked; } window.close(); } function doCancel() { window.returnValue = false; window.close(); } </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>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() { var str; var caseSensitive; } function doSearch() { myDialog.str = ""; myDialog.caseSensitive = false; if (showModalDialog("search.htm", myDialog)==false) return; // user canceled search else { // search for the string } }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.
Top of Page
© 1997 Microsoft Corporation. All rights reserved. Terms of Use.