Why is this page text-only?

JavaScript popups... The right way

This isn't about whether or not you should use popup windows. Everyone hates popups these days but sometimes they're necessary so you should code them properly. I'm always surprised because 90% of sites still do them wrong so here's a quick tip.

Here's how the majority of sites I see have their popup windows coded...

The Not So Good Way

<a href="#" onClick="window.open('whatever.html', 'windowName', 'width=200,height=200');">My Link</a>

The problem with this approach is that the link is entirely embedded in the javascript onClick event so the link will only work via javascript. Why do we care? Two reasons:

  1. Accessibility - Screen readers generally do not have javascript enabled so these links won't work for those users with visual impairments. There are also a small percentage of users who have simply disabled javascript, possibly out of security concerns.
  2. It annoys people like me - As a Firefox user I have a tendency to scan the page and middle-click on any link that looks interesting. This opens each link in a new tab (IE users often right-click and select 'open in a new window'). This lets me read multiple pages without having to click the back button a bunch of times. All hail tabbed-browsing. Popups coded this way prevent me from doing this.

So how should you be coding popup links? Here's the way I like to do it...

The Better Way

<a href="whatever.html" onClick="window.open(this, 'windowName', 'width=200, height=200'); return false;">My Link</a>

This embeds the link in the href attribute where it belongs and uses the javascript 'this' method to reference it. This way the popup works for regular users via the javascript but the link will still work the old fashioned way for screen readers and firefox tabbing. Obviously I'm using inline javascript here but you could easily break this out in a function if you plan on having multiple popup windows on the same page.

Del.icio.us Digg Yahoo! My Web Seed Newsvine reddit Technorati Facebook StumbleUpon Mark in ma.gnolia Google Bookmarks Windows Live

TrackBacks

TrackBack URL for this entry:
http://www.codescene.com/cgi-bin/mt/mt-t.cgi/28

3 Comments

Shouldn't that be "this.href"? Also the "javascript:" is not necessary in the onclick event (but you probably know that since you didn't use it in the first example). And you're missing a quote on the window attributes. Other than that perfect! :-)

Another good practice is to pop the window up to the front (in case you previously opened a window of that name and it is obscured). Plus you can return false only if the window successfully opened.

var w=window.open(this.href,'windowname','')
if (w) { w.focus(); return false; }
return true; /* in case the window did not open */

Mr. Fitzgerald makes some good observations and points out a couple flaws in my hastily written blog entry so I've made some minor changes to it.
Thanks for the feedback!

Leave a comment