How to open popups

by @jehiah on 2005-09-11 03:18UTC
Filed under: All , HTML , Javascript , Web

There is a right way to use even if it normally is used in some evil way. I’m not talking about ways to avoid popup blockers here; just ways to keep your code clean, and your site usable.

If you are looking for a complete reference to go away! You might find one here though.

First let’s have a look at a common use of (don’t copy and paste this. It’s EVIL)

<a href="#" onclick="'path/to/page',pagename)">link title</a>

A few things are wrong here. First the href attribute doesn’t serve it’s design. It should have the reference to the page being opened by the link. This serves a few purposes; even though you as a developer might want the target opened in a new window; it allows the user to open it in a new tab in firefox (or a new window in IE) by right clicking it. It also allows the link to function in a javascript disabled environment. Lastly it gives some feedback via the browsers status bar when a user mouses over the link (many people [myself included] check that out before clicking on links). Oh and you can “copy links” before clicking on them.

Why the pound sign in the href? It is a lazy way to keep the browser from change the current page even after it opens a new window via the onclick event.

A better way to code this would be:

<a href="path/to/page" onclick="'path/to/page',pagename);return false;">link title</a>

This allows users to open the page how they want it, gives feedback in the status bar; and if they have javascript enabled it opens in a new window; leaving the current page alone (thats the return false; part)

I also see <span> tags with onclick attributes that are styled to look like links. Give me a break; If you want a link. Use a link!

UPDATE 2/23/06 : Kudos to Snook for coming up with a prototype powered popup function. Combined with the techniques above you get some nice usability and clean code. It allows you to do this (assuming you update to return false). Another slick simplification is to use this.href instead of re-typing the href in the popup method call.

<a href="path/to/page" onclick="return{url:this.href});">link title</a>

UPDATE 3/27/06 : I’ve added a few features to Snook’s popup script to fully reflect all the options here

Subscribe via RSS ı Email
© 2023 - Jehiah Czebotar