Section 9.2. The window Object


9.2. The window Object

The browser window encompasses the entire browser environment, including parts of the window "chrome" (the part of the browser that surrounds the document), the actual web page, and even the user's experiences.

The window object is global and always present even if its presence is implicitly, rather than explicitly, stated. In previous chapters we've used functions such as alert and eval, and these functions may seem "independent" of any object model. However, they're implicitly a part of the window objectas is the document and other second-level objects, global variables, and other objects not associated with any other object within an object model.

The window has interest beyond being just a parent to all other elements. Through it you can manually set the status in the status bar of the browser, open a new window, resize one that's already open, and then close it again. This is handy if you're providing separate windows for help or additional information, though with the growing popularity of DHTML and Ajax, much of this now occurs within a document rather than a separate window.

The window object methods and properties fall into four categories: creating and managing new windows, manipulating the behavior of existing windows, serving as timers, and being the parent of the other objects in the BOM.

For the first category, creating new windows, three methods provide quick pop-up windows (each for a specific purpose), while a fourth can create a window with as much, or as little, window infrastructure included as you wish.

9.2.1. The Dialogs: Alert, Confirm, and Prompt

The three simple, pop-up window object methods create a window with minimal window chrome; each serves a specific purpose. These are usually referred to as the dialog windows.

We're familiar with the alert dialog, and it's a quick way to provide a message to the person accessing the page. The only parameter it takes is a message string, and it returns no value:

alert("This is the message");

The confirm method creates a dialog with a question and two buttons: Cancel and OK. The message is passed as a parameter, and depending on which button is pressed, either a TRue value is returned (OK) or a false (Cancel):

var result = confirm("Do you want fries with that?");

The prompt opens a window with a field for entering text, as well as the Cancel and OK buttons. It takes two parameters: a message providing the prompt for the response, and a default string, which is used to fill in the text field:

var response = prompt("What's your name?", "Wouldn't you like to know...");

Note that none of these methods are preceded by a reference to the window object; that object is global, and its presence is assumed.

I refer to these types of windows as pop ups because that's basically what they do: pop up. However, this phrase has normally been reserved for those windows that seem to take over your desktop every time you visit a web page. Yes, you know the type: the ones you instruct your browser to prevent.

However, not all windows that open are full of moving bunnies with an invitation to shoot one and win a Big Prize. Opening a separate window can be an effective way to provide additional information, without taking the person away from the current page.

9.2.2. Creating Custom Windows

There are many reasons to create a new window: accessing a help system, providing additional information, reviewing a shopping cart or other information, and yes, even displaying animated bunnies with roving bullseyes.

To open a window and control its contents, size, position, and so on, use the open method. This method takes several parameters, all of which are optional. The first parameter is the URL of the document to open, if any. The second is the name given to the window. This can be used for communication between the parent and child windows, or between siblings if many windows are opened.

The third parameter is a set of window options, all contained in one string and separated by commas. In the following lines of code, a window is created and named "test." It contains a link to the main O'Reilly web site, is 600x400 pixels, and doesn't have a location or toolbar:

window.open("http://oreilly.com","test","width=600,height=400,toolbar=no,location=no");

Not all options can be set in all circumstances. Those that impact certain components of the window frame and layering position of the window can be modified from the default only if the script has a UniversalBrowserWrite privilege, usually granted with script signing. Since the support for this isn't universal, it's best to avoid any dependency on these options.

The common options supported by the majority of browsers, their default values, and their purpose are given in Table 9-1.

Table 9-1. Cross-browser compatible window.open options
OptionPurposeDefault value
alwaysLowered

Referred to as "pop under" window. Puts window under parent window unless parent window is minimizedDefault is no; defined to work only with UniversalBrowserWrite
alwaysRaised

Opens window on top of parent windowDefault is no; defined to work only with UniversalBrowserWrite
dependent

Opens a window dependent on parent window. When parent closes, all dependent windows closeDefault is no
directories

Displays personal bookmarks or links bar in browser, depending on browser typeDefault is yes;can be overridden by user in some browsers
height

Height of content area in pixelsMinimum of 100 pixels
width

Width of content area in pixelsMinimum of 100 pixels
outerHeight

Height of entire browser window, in pixelsMinimum of 100 pixels
outerWidth

Width of entire browser window, in pixelsMinimum of 100 pixels
top

Position of topmost edge of browser windowMust be positioned onscreen
left

Position of leftmost edge of browser windowMust be positioned onscreen
menubar

If yes, renders the menubarCan be overridden by user in some browsers
toolbar

If yes, renders the toolbarCan be overridden by user in some browsers
location

If yes, renders location or address barIE7 forces the location to always display
status

If yes, renders the status bar at bottom of browser windowDefaults to yes for some browsers
resizable

If yes, the window is resizableCan be overridden by user in some browsers
scrollbars

If yes, the window has scrollbars (if the loaded document doesn't fit)Can be overridden by user in some browsers
modal

Opens a window that must be closed before returning to the main windowDialog windows are modal window; in some browsers, requires UniversalBrowserWrite
dialog

Opens a dialog window similar in appearance and behavior to alert window 
minimizable

Only when dialog is set to yes; inserts buttons to minimize window 
titlebar

Renders or removes titlebarOn by default; requires UniversalBrowserWrite; may be overridden by users in some browsers
close

Renders or removes close button (icon)On by default; requires UniversalBrowserWrite; may be overridden by users in some browsers


As you can see, security is a real concern when it comes to pop-up windows. When I first started using JavaScript, anything went; back then, sites would use hidden windows to try out their deviltry, or size other windows and force them to the front so you couldn't work around them. Then there were the windows without a visible ability to close. It was an ugly time in JavaScript. Luckily, most of this is behind us.

Example 9-1 is an application that uses a prompt dialog to get a string to open a new window. Try out variations of the option string, and see the differences. Note that you'll be prompted to allow pop ups when you test the page.

Example 9-1. Using a prompt dialog to get window open options

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Windows</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <script type="text/javascript"> //<![CDATA[ var optionString = prompt("Enter your option string"); optionString = optionString ? optionString : ""; document.writeln("Options are: " + optionString); window.open("http://oreilly.com","test",optionString); //]]> </script> </body> </html>

If no option string is specified, the newly opened browser will, most likely, resemble the parent window. If some options are specified, otherssuch as toolbar, location, and menubarmay be off by default and dependent on the browser you're using.

JavaScript Best Practice: Specify a value for all options when opening a window; avoid using any option that makes the window less accessible or that demonstrates a different behavior across browsers.


There are other options when opening a window, but many violate accessibility standards, and most are implemented only in older browsers, or one or two modern browsers. An example of this is fullscreen. This opens a browser to fill the screen, which is intimidating to users and a vile option. Mozilla/Firefox do not implement this. Other browsers might, but think carefully before trying it with your JavaScript applications.

Once you have a window object, you can adjust it from the parent window or have a window adjust itself. The methods to manage this are covered next.

An excellent page covering the different options, the security associated with each, and which browsers they're implemented in, can be found at http://developer.mozilla.org/en/docs/DOM:window.open.


9.2.3. Cross-Window Communication

Once you have a window, you can have a little bit of fun. Among the methods that can manipulate a window are those that affect its size, focus, and position. This is true not just of windows that open, either. If you want to manipulate the window that contains the script containing the manipulating code, you can use self to refer to the window.

In the following code, the window containing the JavaScript being run is moved to a position of 0,0 for top and left:

self.moveTo(0,0);

If, instead, you want to reference a window you open from code, you'll need to capture the window reference, returned from the window.open call:

var newWindow = window.open("http://somecompany.com","NewWindow", "...options..."); newWindow.moveTo(0,0);

The opening window can reference any of those it opens using a reference to the window. This new window can also reference the window that opened it using the opener keyword:

opener.moveTo(0,0);

Each window can invoke the other window's methods, including getting access to the window objects, document, frames, location, and so on. There are few limitations to this cross-window communication, other than that most browsers do not let the opened window close the original window. Rightfully so, because closing the original window could lose the user's back-button history, opened tabs, half-filled fields, and so on. Those that do support this behavior provide a note to the user getting permission to close the window.

Once you have a reference to a window (either through an open window reference, through self, or through opener), each can be dynamically manipulated, as discussed in the next section.

9.2.4. Modifying the Window

Once you create a pop-up window, you can set the focus to that window, or reset it back to the opening window through the focus method. Using blur, you can also reset the focus to whatever next window would normally get the focus:

newWindow.focus(  ); ... newWindow.blur(  );

You can get an interesting effect by opening a window that's smaller than the opener and then resetting focus back to the opener. This effectively hides the pop-up window.

You can also resize a window using either the resizeBy or resizeTo methods. The resizeBy method works on the current window dimension, adjusting the current values by those specified as the parameters. The first is how much to adjust the width of the window; the second, the height:

newWindow.resizeBy(50,50);

The resizeTo method resizes the window to a specific width and height:

opener.resizeTo(100,100);

One of the more helpful methods is moveTo, which moves a window's upper-left corner to a given x-y dimension:

self.moveTo(x,y);

You can use this approach to open context-sensitive help windows that are positioned exactly where an event occurs. In Example 9-2, a page with a single form element is opened; a red-colored block underneath has the words "Push for Help." In script, an event listener is attached to this block to capture the click event. When the page opens, the focus is set to the form element in order for a person to type in his name. Of course there's no submit button, so it's not surprising that the user would then click the "Push for Help" button to get help.

Example 9-2. Opening a help window

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Cross-Window Communication</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <script type="text/javascript"> //<![CDATA[ window.onload=setObjects; function setObjects(  ) {    document.forms[0].elements[0].focus(  );    var evtObject = document.getElementById("panicbutton");    // test for object model    if (evtObject.addEventListener) {       evtObject.addEventListener("click",openHelp,false);    } else if (evtObject.attachEvent) {       evtObject.attachEvent("onclick", openHelp);    } else if (evtObject.onclick) {       evtObject.onclick=openHelp;    } } function openHelp(x) {    var optionString = "width=200,height=100,menubar=no,toolbar=no,scrollbars=no,location=no,resizeable=no";    var helpWindow = window.open("help.htm","test",optionString);    helpWindow.focus(  );    helpWindow.moveTo(x.screenX,x.screenY);    return false; } //]]> </script> <form name="currentForm"> Your name: <input type="text" size="50"> </form> <div  style="width:100px;height:20px;background-color:#f00; padding: 5px;margin:10px auto"> Push for Help </div> </body> </html>

A small window opens with minimum chrome, located just below and to the right of where the click has happened. The reason it's positioned based on the click event is that when the window is opened, it's moved to the screen location of the click event. Once opened, the focus is set to this window.

Example 9-3 contains the contents of the window that opens. It actually accesses the opener window, finds the form element, and copies whatever value it has. This provides a message in the window, which also has a link to close the window.

Example 9-3. Opened window

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <p>Helpful Information.</p> <script type="text/javascript"> //<![CDATA[ var nmStr = opener.document.forms[0].elements[0].value; document.writeln("Hello " +  nmStr + "!"); //]]> </script> <p><a href="javascript:self.close(  );opener.resizeTo('100','100')">close window</a></p> </body> </html>

This is an obnoxious little help window. When the window close link is clicked, an embedded script will close the window, yes, but it will also resize the opener to the minimum most browsers will allow within the JavaScript sandbox. A surprising number of browsers allow this behavior, including Firefox and Safari, though Opera is well behaved in this regard.

Of course, resizing the opener window to an unusable size isn't something I recommend. However, opening a help window, positioning it to where an event occurs, and communicating information between the windows can be very helpful. Later, when we get into Dynamic HTML, we'll create the same effect with hidden page elements, but for now, you have a way to provide context-sensitive help.

Another critical property associated with the window object is the JavaScript timer, covered next.

9.2.5. Timers

Timers are a way to add a dynamic aspect to your web pages. When we start working with DHTML, you'll see that timers are used to create any number of page animations. Even without DHTML, timers can open or close windows, pop up a message to the user, and even destroy a cookie for security purposes.

There are two types of timers: one that's set once, and one that reoccurs over an interval. Both can be canceled, though the one-time timer method fires just once.

To create a nonrepeating timer, use the setTimeout method. It takes a minimum of two parameters: the function literal or function name to run when the timer delay ends, and the length of the timer delay in milliseconds. If there are any parameters to send to the function, they are listed at the end of the call, separated by commas. The method returns the identifier of the timeout:

var tmOut = setTimeout(func, 5000,"param1",param2,...,paramn);

To clear the time out, use the clearTimeout method:

clearTimeout(tmOut);

If you want the timer delay to repeat over an interval, use the setInterval. This takes two parameters, the function name and the timer interval. As with setTimeout, it return an identifier:

Var tmOut = setInterval("functionName", 5000);

Again, to stop or cancel the interval timer, use the clearInterval method. If you want to have a repeating delay but still use a function literal or pass in parameters, you can use setTimeout and reset the timer when the previously set timer expires.

In Example 9-4, a timer is used to reset a document image at the end of each timer delay. We'll get into the document-images collection later, but for now, an image object in the page can be reset to another image, just by setting the image source. The images are from an old animation and game I created using the first versions of DHTML years ago. Changing the images forms a slow, crude animation.

Example 9-4. Using timer to change page image

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Timers</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ var ct = 0; var imgs = new Array("impatient.gif","doomed.gif","upright.gif"); setTimeout("progress(  )",3000); function progress(  ) {    if (ct < 3) {       document.images[0].src=imgs[ct];       ct++;       setTimeout("progress(  )",3000);    } } //]]> </script> </head> <body> <img src="/books/4/327/1/html/2/mad.gif" /> </body> </html>

Note that in the function, if all of the images haven't been displayed, the timer is reset to run again, using the function name. Another approach would be to use setInterval and then clear it once the last image has displayed.

You want to avoid any type of timer operation that could generate a document.write or other method that alters the makeup of the document object. This leaves the page in an unstable state. Instead, modify components of the document rather than the entire document itself.


Up to this point, we've been working with one window and one document. However, with the use of frames, we can segment the page and give each segment a different URL and purpose. Frames are one of the several objects accessible through the main window object, and the first we'll cover.




Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net