start page | rating of books | rating of authors | reviews | copyrights

JavaScript: The Definitive GuideJavaScript: The Definitive GuideSearch this book

13.8. Window Control Methods

The Window object defines several methods that allow high-level control of the window itself. The following sections explore how these methods allow us to open and close windows, control window position and size, request and relinquish keyboard focus, and scroll the contents of a window. We conclude with an example that demonstrates several of these features.

13.8.1. Opening Windows

You can open a new web browser window with the open( ) method of the Window object. This method takes four optional arguments and returns a Window object that represents the newly opened window. The first argument to open( ) is the URL of the document to display in the new window. If this argument is omitted (or is null or the empty string), the window will be empty.

The second argument to open( ) is the name of the window. As we'll discuss later in the chapter, this name can be useful as the value of the target attribute of a <form> or <a> tag. If you specify the name of a window that already exists, open( ) simply returns a reference to that existing window, rather than opening a new one.

The third optional argument to open( ) is a list of features that specify the window size and GUI decorations. If you omit this argument, the new window is given a default size and has a full set of standard features: a menu bar, status line, toolbar, and so on. On the other hand, if you specify this argument, you can explicitly specify the size of the window and the set of features it includes. For example, to open a small, resizeable browser window with a status bar but no menu bar, toolbar, or location bar, you could use the following line of JavaScript:

var w = window.open("smallwin.html", "smallwin",
                    "width=400,height=350,status=yes,resizable=yes"); 

Note that when you specify this third argument, any features you do not explicitly specify are omitted. See Window.open( ) in the client-side reference section for the full set of available features and their names.

The fourth argument to open( ) is useful only when the second argument names an already existing window. This fourth argument is a boolean value that specifies whether the URL specified as the first argument should replace the current entry in the window's browsing history (true) or create a new entry in the window's browsing history (false), which is the default behavior.

The return value of the open( ) method is the Window object that represents the newly created window. You can use this Window object in your JavaScript code to refer to the new window, just as you use the implicit Window object window to refer to the window within which your code is running. But what about the reverse situation? What if JavaScript code in the new window wants to refer back to the window that opened it? In JavaScript 1.1 and later, the opener property of a window refers to the window from which it was opened. If the window was created by the user instead of by JavaScript code, the opener property is null.

An important point about the open( ) method is that it is almost always invoked as window.open( ), even though window refers to the global object and should therefore be entirely optional. window is explicitly specified because the Document object also has an open( ) method, so specifying window.open( ) helps to make it very clear what we are trying to do. This is not just a helpful habit; it is required in some circumstances, because, as we'll learn in Chapter 19, event handlers execute in the scope of the object that defines them. When the event handler of an HTML button executes, for example, the scope chain includes the Button object, the Form object that contains the button, the Document object that contains the form, and, finally, the Window object that contains the document. Thus, if such an event handler refers merely to the open( ) method, this identifier ends up being resolved in the Document object, and the event handler opens a new document rather than opening a new window!

We'll see the open( ) method in use in Example 13-4.

13.8.2. Closing Windows

Just as the open( ) method opens a new window, the close( ) method closes one. If we've created a Window object w, we can close it with:

w.close( ); 

JavaScript code running within that window itself could close it with:

window.close( ); 

Again, note the explicit use of the window identifier to disambiguate the close( ) method of the Window object from the close( ) method of the Document object.

Most browsers allow you to automatically close only those windows that your own JavaScript code has created. If you attempt to close any other window, the user is presented with a dialog box that asks him to confirm (or cancel) that request to close the window. This precaution prevents inconsiderate scripters from writing code to close a user's main browsing window.

In JavaScript 1.1 and later, a Window object continues to exist after the window it represents has been closed. You should not attempt to use any of its properties or methods, however, except to test the closed property. This property is true if the window has been closed. Remember that the user can close any window at any time, so to avoid errors, it is a good idea to check periodically that the window you are trying to use is still open. We'll see this done in Example 13-4.

13.8.3. Window Geometry

In JavaScript 1.2, moveTo( ) moves the upper-left corner of the window to the specified coordinates. Similarly, moveBy( ) moves the window a specified number of pixels left or right and up or down. resizeTo( ) and resizeBy( ) resize the window by an absolute or relative amount; they are also new in JavaScript 1.2. Note that in order to prevent security attacks that rely on code running in small or offscreen windows that the user does not notice, browsers may restrict your ability to move windows offscreen or to make them too small.

13.8.4. Keyboard Focus and Visibility

The focus( ) and blur( ) methods also provide high-level control over a window. Calling focus( ) requests that the system give keyboard focus to the window, and blur( ) relinquishes keyboard focus. In addition, the focus( ) method ensures that the window is visible by moving it to the top of the stacking order. When you use the Window.open( ) method to open a new window, the browser automatically creates that window on top. But if the second argument specifies the name of a window that already exists, the open( ) method does not automatically make that window visible. Thus, it is common practice to follow calls to open( ) with a call to focus( ).

focus( ) and blur( ) are defined in JavaScript 1.1 and later.

13.8.5. Scrolling

The Window object also contains methods that scroll the document within the window or frame. scrollBy( ) scrolls the document displayed in the window by a specified number of pixels left or right and up or down. scrollTo( ) scrolls the document to an absolute position. It moves the document so that the specified document coordinates are displayed in the upper-left corner of the document area within the window. These two methods are defined in JavaScript 1.2. In JavaScript 1.1, the scroll( ) method performs the same function as the JavaScript 1.2 scrollTo( ) method. scrollTo( ) is the preferred method, but the scroll( ) method remains for backward compatibility.

In JavaScript 1.2, the elements of the anchors[] array of the Document object are Anchor objects. Each Anchor object has x and y properties that specify the location of the anchor within the document. Thus, you can use these values in conjunction with the scrollTo( ) method to scroll to known locations within the document. Alternatively, in IE 4 and later and Netscape 6 and later, document elements all define a focus( ) method. Invoking this method on an element causes the document to scroll as needed to ensure that the element is visible.

13.8.6. Window Methods Example

Example 13-4 demonstrates the Window open( ) , close( ), and moveTo( ) methods and several other window-programming techniques that we've discussed. It creates a new window and then uses setInterval( ) to repeatedly call a function that moves it around the screen. It determines the size of the screen with the Screen object and then uses this information to make the window bounce when it reaches any edge of the screen.

Example 13-4. Moving a window

<script>
// Here are the initial values for our animation
var x = 0, y = 0, w=200, h=200;  // Window position and size
var dx = 5, dy = 5;              // Window velocity
var interval = 100;              // Milliseconds between updates

// Create the window that we're going to move around
// The javascript: URL is simply a way to display a short document
// The final argument specifies the window size
var win = window.open('javascript:"<h1>BOUNCE!</h1>"', "", 
                      "width=" + w + ",height=" + h);

// Set the initial position of the window
win.moveTo(x,y);

// Use setInterval( ) to call the bounce( ) method every interval 
// milliseconds. Store the return value so that we can stop the
// animation by passing it to clearInterval( ).
var intervalID  = window.setInterval("bounce( )", interval);

// This function moves the window by (dx, dy) every interval ms
// It bounces whenever the window reaches the edge of the screen
function bounce( ) {
    // If the user closed the window, stop the animation
    if (win.closed) {
        clearInterval(intervalID);
        return;
    }

    // Bounce if we have reached the right or left edge
    if ((x+dx > (screen.availWidth - w)) || (x+dx < 0)) dx = -dx;

    // Bounce if we have reached the bottom or top edge
    if ((y+dy > (screen.availHeight - h)) || (y+dy < 0)) dy = -dy;

    // Update the current position of the window
    x += dx;
    y += dy;

    // Finally, move the window to the new position
    win.moveTo(x,y);
}
</script>

<!-- Clicking this button stops the animation! -->
<form>
<input type="button" value="Stop" 
       onclick="clearInterval(intervalID); win.close( );">
</form>


Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.