How to open windows with JavaScript the Right Way

August 24, 2004 at 12:45 am (PT) in Programming

All too often I see web sites open new browser windows using HTML and JavaScript code such as:

<a href="#" onClick="window.open('foo.html');"> <!-- BAD! -->

or:

<a href="javascript:window.open('foo.html');"> <!-- BAD! -->

This is one of my biggest peeves. Here’s why:

  • For the first case, when users click on the link, a new window will appear, but the original window will scroll to the top of the page, causing the users to lose their place. In many cases this defeats the point of opening a new window at all.
  • The first case prevents the browser from marking visited links properly. This compounds the problems of my first point.
  • Both cases make the link completely useless in browsers that don’t have JavaScript enabled.
  • Both cases prevent users from right-clicking on the link and explicitly requesting a new window. Instead of a new window going to the desired page, they’ll get a new window with the original page (in the first case) or with a blank page (in the second case).

Better:

<a href="foo.html" onClick="window.open('foo.html');return false;">

This solves all of the problems above. The “return false” is important! When the onClick event handler returns false, a browser does not follow the href link.

Better yet:

Re-evaluate why you want to open links in new windows at all. Most browsers have an “Open in New Window” command; if users want new windows, let them ask for it.