The Window Open Method

A method is a behavior or action that some JS element can perform. Since it is difficult to visualize this abstract term, an example is a good way to illustrate what methods are.

The Window Open Method

On many occasions a new browser window will open when a link or a button is clicked. The script below uses window.open to open a new browser window. Notice that window.open is not a property of window, rather it is a method (an action).

<script language="JavaScript">
function openNewWindow() {
NewWindow=window.open("http://www.yahoo.com", "awindow", "width=350,height=300");
}

</script>

You can create a link that when clicked executes the function above like this:

<a href="javascript:openNewWindow();">Open New Window</a>

As with all links, the beginning and ending anchor tags are used, but notice that the URL is replaced by javascript: followed by the function to be executed.


Controls and Options for Opening a New Window

You can turn on or off many of the features you see in a normal browser window. In the openNewWindow function above, only the width and height of the window has been specified. Because we did not explicitly remove toolbars, scrollbars, etc, they are included in the new window. A table of the most often used window properties is found below.

Property
Description
Number of pixels, or to Remove Feature
width width of new window in pixels width=n
height height of new window in pixels height=n
toolbar Shows/hides toolbar toolbar=0
menubar Shows/hides menubar menubar=0
scrollbars Shows/hides scrollbars scrollbars=0
resizable Allows/disallows resizing resizable=0
status Shows/hides status bar status=0
location Shows/hides location bar location=0
left Distance in pixels from left side of original screen left=n
top Distance in pixels from top of original window top=n
alwaysRaised The new window is always on top of the original window alwaysRaised=1
Note: this feature is off by default. A value of 1 activates it.

A function with the window.open method below sets the size of the window to 300, the width to 200, turns off the toolbar, menubar, scrollbars, status bar and location bar. The window is resizable and is located 30 pixels to the left and 30 from the top of the parent window.

NewWindow=window.open("http://www.yahoo.com", "awindow", "height=300,width=200,toolbar=0,menubar=0,scrollbars=0,resizable=1,
status=0,location=0,left=30,top=30");


Exercise

1. Type the script below into Notepad.
2. Save it on the desktop with an .HTM or .HTML extension.
3. Double click the file to open it in a browser.
4. If there are no typos, your web page should look like this.

<html>
<head>
<title>Open New Window</title>

<script language="JavaScript">
function openNewWindow() {
NewWindow=window.open("http://www.yahoo.com", "awindow", "width=350,height=300,");
}
</script>
</head>

<body>
The link below will open a new window.<br>
<a href="javascript:openNewWindow();">Open New Window</a>
</body>
</html>