Tuesday, December 4, 2007

Popups in Javascript

Sometimes it's useful to add a popup to your pages. When the user clicks on a link, a new window opens and displays a page.

There are two ways to do this. You can add a TARGET="_blank" to the -tag, but this simply opens a new browser window that completely obscures the old one.

This may be what you want, but at other times a small window on top of the large browser window is much better. This small window is popularly known as a popup.

First the basic syntax of how to create a popup, then an explanation of the script, including a table of the most common arguments you can give to a popup and the problem of focusing.
Then a new way of adding popup behaviour to a link. This site uses the new system because it's much cleaner than the old one.
Finally some notes about writing content directly into the popup. This gives several problems, most importantly the confusion over exactly what the URL of the popup is.

This page only treats the opening of popups. For communication between the opening window and the popup, see the Cross-window scripting page.

Creating a popup

To create a popup you'll need the following script:


Then, you link to it by:

Link to popup

Open popup.

See below for a far cleaner way of adding popup behaviour to a link.

Explanation

First, you open the new window. The page to be opened is passed on by the argument url. Note that, if you want to open a page on another server, Explorer will frequently give errors. This is a feature, not a bug, so there's little you can do about it.

You have to give a name to the window (in this case, name). However, this name is completely useless.

In addition, you have to load the window into a JavaScript variable. The reasons for this are complex and have mostly to do with preventing errors in various browsers, especially when you want more links to lead to the same popup.

function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');

Arguments

So first we define the url to be loaded in the popup and then the useless name.

As third argument, you can assign all kinds of variables. Most common are height and width, which define the height and width of the new window.

'height=200,width=150'

As soon as you define anything, all yes | no arguments that you have not defined are set to no.
Warning: Spaces or hard returns are not allowed within the quote-marks.

Open popup, and set the arguments through the checkboxes below.

dependent
directories
fullscreen
location
menubar
resizable
scrollbars
status
toolbar
top=200
left=400
width=200
height=200
screenX=200
screenY=100

No comments: