[ Team LiB ] Previous Section Next Section

6.5 Bringing a Window to the Front

NN 3, IE 4

6.5.1 Problem

You want to bring a window that is buried beneath other windows back to the top of the pile.

6.5.2 Solution

For any window to which you have a valid reference, invoke the focus( ) method. The following function expands on topics addressed in Recipe 6.4. This expanded function not only opens a subwindow, but brings it forward if it was previously opened, and remains so underneath the main window:

var newWindow;
function makeNewWindow(url) {
    if (!newWindow || newWindow.closed) {
        newWindow = window.open(url,"subwind","status,height=200,width=300");
    } else {
        // window is already open, so bring it to the front
        newWindow.focus( );
    }
}

Thus, if you have a link, button, or other script action that invokes makeNewWindow( ) after the window has been created and (accidentally or intentionally) hidden, the next activation of the function brings the new window into view.

6.5.3 Discussion

A global variable, newWindow in the preceding example, is initialized as null when the main page loads. The first time the makeNewWindow( ) method is called, the first conditional expression evaluates to true because the variable is still null. The new window is created, and the variable now holds a reference to the subwindow. Let's say that rather than closing the subwindow, the user clicks somewhere on the main window, causing the subwindow to submarine underneath the main window. If the user clicks on the button that invokes makeNewWindow( ) again, the first if condition fails (because newWindow contains an object reference), but a test of the closed property of the subwindow returns false. Execution branches to the alternate section, invoking the focus( ) method on the new window.

You can begin to see in this example how valuable it is to maintain a reference to the subwindow when you create it with window.open( ). But you also have to be careful to check with the closed property before referencing the object to do things like giving it focus or closing it via the close( ) method. Once you assign the subwindow's reference to the variable, the reference doesn't go away when the window closes. The variable still contains what it thinks is a valid window object reference. But when you attempt to use that reference in a statement to access one of its methods or properties, the reference fails, leading to a script error. And, since you cannot control whether a user closes a subwindow or leaves it open, it's up to your scripts to do the checking behind the scenes.

6.5.4 See Also

Recipe 6.4 for opening multiple windows by script; Recipe 6.9 for a simulated cross-browser modal window that always stays on top.

    [ Team LiB ] Previous Section Next Section