target="_blank" in External LinksLove it or hate it, many authors prefer to have links that are external to
their sites open up in new browser windows. This is typically done through the
use of target attributes on those links. However, as you may be
aware, the target attribute is not valid for links when authoring
in the Strict flavors of either HTML 4.01 or XHTML 1.0.
The JavaScript on this page gets around this problem in a standards-friendly
manner. An onload event handler is attached to the document that
goes through all the links looking for a class value of "external"
and attaches an onclick handler to each link it finds with one. That handler
opens a new window using the link's href value.
There's no reason you couldn't move the JavaScript to an external file and
then use it all over your site. (I just included it here in a script
element to make viewing the source easier.) And, worst-case scenario, if a
visitor's browser can't handle it or has JavaScript disabled, the links will
still work as plain-old links.
Here are a handful of internal and external links for you to test out:
Ideally, there's really no need for the class attribute, or any extra
information beyond the link's href value for that matter, since the URL is
enough to be able to tell whether the link is external or internal. The links
could be styled appropriately using a technique like
this one from Stuart Langridge at kryogenix.org
and the JavaScript could easily be changed to use similar logic in evaluating
the links' href values. Something a little like this:
“Better” Standards-based Replacement for target="_blank" in External Links
If you're not going to style external links any differently, or if you can live without the styles being applied correctly in all browsers, I would actually recommend using that version, since you can apply it to an existing page without having to go through adding class attributes to all your links.