JavaScript Popup Windows

You can use JavaScript to create popup windows. Popup windows are different to simply opening a new browser window.

If you only want to open a new browser window you can add the target="_blank" attribute within the <a> element (see this article on opening a new window in HTML).

JavaScript popup windows however, are more powerful. Using JavaScript's method, you can determine what the window looks like (i.e. size, whether it has scrollbars, status bars etc).

Basic JavaScript Popup Script

Here is the basic script for generating a popup window:

This code is best placed inside a function (see below). But first things first. Here's an explanation of the above code.

The method takes three arguments: the URL of the new page, the name of the window, and the attributes of the window. The attributes are optional and should be quite self explanatory in the above example. You can change these to see how it affects the popup window.

Basic Function for Popup Windows

You can put the above code into a function, then call the function, passing the URL as a parameter, whenever you want to open a popup window.

Doing this allows you to cut down on the amount of code you use when using popups.

Here's a working example.

The JavaScript:

The above script creates a function that accepts a parameter called "url". You can now call the function in your HTML as follows.


Here, we create a normal HTML link, but we also add the onclick event handler to trigger our JavaScript function. In the script, we use this.href to refer to the HTML link (saves us typing it out twice). This piece is the "url" parameter that we're passing to the function.

The return false bit ensures our base page doesn't actually go to that address - only the popup window.


So, putting the two together, our code should work like this:

But wait!

You can make your function even more portable by using the script below.

A Better Script

This script is more versatile than the above script. This is because the function accepts parameters for more of the popup's properties (ie. height, width, position, name). This means you won't need to create a new function every time you want a different sized popup, a popup with a different name, or a popup in a different position.

Automatically Center your Popup

This function centers the popup in the middle of the users' screen. The JavaScript code will detect the screen size (each user could have a different screen size), then position the popup window in the center.

So, if you need the popup centered in the middle of the users' screen, use the following code:

Close the Popup Window

You can use the JavaScript close() method to close the popup window.

For example, to create a hyperlink that closes the window, you could do this:

For more information, see Close Popup Window.