How to Open Windows with JavaScript the Right Way


All too often, I see sites open windows using HTML code such as:

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

or as:

    <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, and
  users will 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.

* 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).

A better way:

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

This solves all of the problems above.  The "return false" part at the end
is important!  Browsers will not follow the HREF link when the onClick
event handler returns false.


                                                             ... more stuff
___________________________________________________________________________
page updated: 2003-02-04                       home . about . stuff . links
copyright (c) 2003 james lin