Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org

Related items

Almost complete control of pop-up windows

Popup Date Selector

Dictionary Popup Utility

The JavaScript Pop-up Window Primer

You are here: irt.org | Articles | JavaScript | Window | The JavaScript Pop-up Window Primer [ previous next ]

Published on: Monday 9th November 1998 By: Martin Webb

Introduction to JavaScript Pop-up Windows

For most people, the main browser window is the only one they ever use or need. However, it is possible for another window to be opened up to allow you to either view another page while retaining the existing page in the main window, or to open up a remote window that can control or be controlled by the main browser window.

Another browser window can be simply opened using HTML and the TARGET attribute, either in a link or on a form:

<a href="testpage.htm" target="anotherWindowName">Open new window</a>

or:

<form action="testpage.htm" target="anotherWindowName">
<input type="submit" value="Open new window">
</form>

As long as the TARGET attribute specifies a window name that is not already open, a new window will be created mimicing the existing window. If the window already exists, then the contents will be changed instead.

The problem with this approach is that apart from the window name there is nothing in common between the two windows. You can change the location of the new window using a similar link for form target - but that's it. Whereas using JavaScript and the window.open() method, it is possible to control the look and feel of the new window, to have control over its contents, and also to be controlled by the new window.

Window open syntax

The syntax of the open() method is fairly straight forward:

windowHandle = window.open([URL [, windowName [, features]]])

In addition to this, MSIE4 has a fourth parameter:

windowHandle = window.open([URL [, windowName [, features [, replace]]]])

windowHandle
The result of the open() method is returned and held in the variable to the left of the assignment operator (=). This is a reference or handle to the newly opened window. It can be used to close the window, and to interrogate and alter the windows properties - more on this later.

URL
This is the relative or absolute URL of the file to be loaded into the pop-up window, for example:

<script language="JavaScript"><!--
var myWindow = window.open('http://www.irt.org/');
//--></script>

<a href="javascript:window.open('nextpage.htm')">Open Next Page</a>

<form>
<input type="button" onClick="window.open('picture.gif')">
</form>

If no URL is specified, a new window with about:blank will be displayed.

windowName
This is the target name of the new window. So you could load another document into it with:

<script language="JavaScript"><!--
window.open('testpage.htm','myWindow');
//--></script>

<a href="filename.html" target="myWindow">load file into popup window</a>

Features
The third parameter can hold a large selection of name-value pairs:

NN2.0+ValueDescription
directories boolean Controls the standard browser directory buttons
height numeric Specifies the height of the window in pixels
location boolean Controls the Location entry field
menubar boolean Controls the menu at the top of the window
resizable boolean Controls the ability to resize the window
scrollbars boolean Controls the horizontal and vertical scrollbars
status boolean Controls the status bar at the bottom of the window
toolbar boolean Controls the standard browser toolbar
width numeric Specifies the width of the window in pixels

If you don't specify the width or height values, then Netscape browsers will mimic the size of the current window, if you don't specify any attributes then Netscape will mimic all the features of the current window:

window.open('testpage.htm','myExample2');

Note all the name-value pairs must be separated by commas, but must not have spaces between them. For example, the following is incorrect:

window.open('testpage.htm','myExample2','location=yes,  menubar=yes');

Whereas the following, which does not have spaces, is correct:

window.open('testpage.htm','myExample3','location=yes,menubar=yes');

The values for the boolean parameters may be 0 or 1 or yes or no. If a particular boolean parameter is not specified then its value defaults to no. For example, to open a window without directory buttons, location field, menubar, scrollbars, status or toolbar and not resizable use:

window.open('testpage.htm','myExample4','width=200,height=200');

Again, if you don't specify the width and height then the page mimics the current window.

However, to create a window with all the window features you need to explicitly include them:

window.open('testpage.htm','myExample5','width=200,height=200,directories=yes,location=yes,menubar=yes,scrollbars=yes,status=yes,toolbar=yes,resizable=yes');

Replace
The fourth parameter is an optional boolean value, either true or false, which in MSIE4.0+ replaces the current history entry with the new page being loaded (i.e., the last location in the browsers history object is overwritten by the new location).

Stringing it together

So now that we know how to create a window with any features we desire, how can we use JavaScript to control the features we want? The first three parameters are all strings; JavaScript can manipulate strings just as well as any other programming language.

<script language="JavaScript"><!--
function createWindow(what) {
    var URL = what.URL.value;

    var windowName = what.windowName.value;

    var features =
        'width='        + what.width.value +
        ',height='      + what.height.value +
        ',directories=' + (what.directories.checked - 0) +
        ',location='    + (what.location.checked - 0) +
        ',menubar='     + (what.menubar.checked - 0) +
        ',scrollbars='  + (what.scrollbars.checked - 0) +
        ',status='      + (what.status.checked - 0) +
        ',toolbar='     + (what.toolbar.checked - 0) +
        ',resizable='   + (what.resizable.checked - 0);

    window.open (URL, windowName, features);
}
//--></script>

<form>
URL <input type="text" name="URL" value="testpage.htm">
Name <input type="text" name="windowName" value="myWindow">
Width <input type="text" name="width" value="200">
Height <input type="text" name="height" value="200">
<input type="checkbox" name="directories"> Directories
<input type="checkbox" name="location"> Location
<input type="checkbox" name="menubar"> Menubar
<input type="checkbox" name="scrollbars"> Scrollbars
<input type="checkbox" name="status"> Status
<input type="checkbox" name="toolbar"> Toolbar
<input type="checkbox" name="resizable"> Resizable
<input type="button" value="Create It"
    onClick="createWindow(this.form)">
</form>

Which you can try out for yourself:

URL Name Width Height
Directories Location Menubar Scrollbars
Status Toolbar Resizable

Managing Your Windows

Maintaining their focus and keeping them centered

You may have noticed that its quite easy to lose pop-up windows - they can become hidden behind the main browser window. This happens when the main browser window regains focus, i.e., becomes the selected window. To avoid this you need to decide whether you want the pop-up window to have exclusive control of the browser, or whether you want it to be closed, or even brought to the front after a short delay.

By placing the following in the document loaded into the pop-up window then the pop-up will remain in front of the main browser window:

<body onBlur="window.focus()">

This has the side effect on some browsers of inhibiting the use of the main browser window until the pop-up window is closed. If you don't require this feature then you could always refocus the pop-up window after a delay:

<body onBlur="setTimeout=('window.focus()',1000)">

Which ensures that the pop-up window regains the focus after a delay of one second - enough time to allow the user to interact with the main browser window.

Of course you may decide that if the user has moved the focus to the main browser window, that the pop-up window should be closed:

<body onBlur="window.close()">

Keeping windows centered

In NN4, the screenX and screenY attributes were introduced. In MSIE4 the top and left attributes were introduced. By combining the two both NN4 and MSIE4 will allow you to position the window. In earlier browsers the attributes and their values will be safely ignored:

window.open('testpage.htm','myExample6','width=200,height=200,
screenX=400,screenY=400,top=400,left=400');

To actually center the pop-up window requires the use of the window objects outerWidth and outerHeight properties in NN4 and the screen objects width and height properties in MSIE4. However, this results in the pop-up window being centered within the confines of the main browser window in NN4, and centered within the confines of the screen in MSIE4 - not the same thing, unless the main browser window is maximized.

<script language="JavaScript"><!--
function centerWindow() {
    if (document.all)
        var xMax = screen.width, yMax = screen.height;
    else
        if (document.layers)
            var xMax = window.outerWidth, yMax = window.outerHeight;
        else
            var xMax = 640, yMax=480;

    var xOffset = (xMax - 200)/2, yOffset = (yMax - 200)/2;

    window.open('testpage.htm','myExample7',
    'width=200,height=200,screenX='+xOffset+',screenY='+yOffset+',
    top='+yOffset+',left='+xOffset+'');
}

centerWindow();
//--></script>

New Window Features

Both NN4 and MSIE4 introduced new window features that can be set when opening up a new window:

NN4.0+ValueDescription
alwaysLowered boolean Creates a new window that floats below other windows, whether it is active or not.
alwaysRaised boolean Creates a new window that floats on top of other windows, whether it is active or not.
dependent boolean Creates a new window as a child of the current window, i.e., it closes when its parent window closes.
hotkeys boolean Enables or disables most hotkeys in new window that has no menu bar.
innerHeight numeric Specifies the height, in pixels, of the window's content area. Replaces height.
innerWidth numeric Specifies the width, in pixels, of the window's content area. Replaces width.
outerHeight numeric Specifies the vertical dimension, in pixels, of the outside boundary of the window.
screenX numeric Specifies the distance the new window is placed from the left side of the screen.
screenY numeric Specifies the distance the new window is placed from the top of the screen.
titlebar boolean Controls whether the windows has a title bar.
z-lock boolean Controls whether a window rises above other windows when activated.
MSIE4.0+ValueDescription
fullscreen boolean Specifies whether to display the browser in a full-screen or normal window.
channelmode boolean Specifies whether to display the window in theater mode and show the channel band.

In NN4, to create a window smaller than 100 pixels high by 100 pixels wide then signed scripts will be required, other features like setting a window as always lowered or offscreen also require signed scripts - this is to avoid a window that the user cannot see.

To find out more about using signed scripts in NN4 see Chapter 7, JavaScript Security, in Netscape's JavaScript Guide.

Controlling Pop-up Windows

The windowHandle allows you to control the contents of the pop-up window; either to change the location of the pop-up window, to write HTML code into the window, or to interrogate the window properties.

Changing Location

The following shows how to alter the location of the pop-up window from blank.htm to testpage.htm:

<script language="JavaScript"><!--
myWindow8 = window.open('blank.htm','myExample8','width=200,height=200');
myWindow8.location.href = 'testpage.htm';
//--></script>

There are potential problems with the code above. There are occasions where the window may not actually be opened before the change of location is attempted. It is best to change the above code to introduce a slight delay to give the browser a chance to actually open the window first. The following introduces a one second delay before the location is changed:

<script language="JavaScript"><!--
myWindow8 = window.open('blank.htm','myExample8','width=200,height=200');
setTimeout("myWindow8.location.href = 'testpage.htm'",1000);
//--></script>

Writing things down

The following demonstrates how to write directly to the pop-up window using the windowHandle in conjunction with the documents write method. The first occasion that the window is written to will cause the existing contents to be replaced, other following document writes append information to the window.

<script language="JavaScript"><!--
myWindow9 = window.open('testpage.htm','myExample9','width=200,height=200');

function update() {
    for (var i=0; i < 10; i++)
        myWindow9.document.write('Message number ' + i + '<br>');
}

setTimeout('update()',1000);
//--></script>

Interrogation

With frames in a frameset its fairly straight forward to access the parent frame or the child frame, all you need to do is remember the object hierarchy. For example, the following frameset:

<frameset cols="50%,50%>
<frame src="one.htm" name="left">
<frame src="two.htm" name="right">
</frameset>

Produces the following structure:

             Parent Frame
                  |
             +----+----+
             |         |
          one.htm   two.htm

To access the parent frame from one.htm, use simply use: alert(parent.location.href), which will highlight the location of the parent frame, and similarily, to perform the reverse alert(window.one.location.href) will highlight the location of the left frame from the parent frame, and alert(parent.two.location.href) will highlight the location of the right frame from the left frame.

Once you've established this simple object syntax, you can use it to read and write almost any property of any other window within the frameset.

However, when you've opened a new window, the window does not form part of a frameset - therefore a new means of accessing the new window from the opener (i.e., the window that opens the new window) is required and vice versa.

Well, accessing the new window is straight forward enough, you just use the window name as shown in the previous example. Modern browsers also include a means of accessing the opener window. Funny enough, by providing an opener property, e.g., window.opener, which will reference the window, if any, that opened the current window. For example alert(window.opener.location.href) will highlight the location of the current window's opener.

Unfortunately, the opener property was not made available in older browsers - it was introduced in NN3 - but, we are able to create our own window properties/variables at any time:

<script language="JavaScript"><!--
myWindow10 = window.open('blank.htm','myExample10','width=200,height=200');
if (newWindow10.opener == null)
    newWindow10.opener = self;
//--></script>

Which checks to see whether the new window already has an opener property, and if not, creates one with a reference to the current window. This new window property can be used as if the browser supplied the opener property itself.

Date pop-up window

To round of this article, I've included a practical example of using pop-up windows. The form button, when pressed, opens up a date selector. Once a date has been selected the date is returned to the form on this page.

The date selector is described in detail in the article Popup Date Selector

This article has attempted to show you how to create new windows with properties and attributes that you can specify yourself. We have also seen how to write to these windows and how to access one window from another. Hopefully this will encourage you to make more use of the windows open() method.

Related items

Almost complete control of pop-up windows

Popup Date Selector

Dictionary Popup Utility

©2018 Martin Webb