External links in new windows without using 'target'

The default Drupal 5.0 theme (and previous default Drupal themes) uses XHTML Strict. There are reasons this is probably a bad idea but, in the spirit of eating my own dogfood, I'm going with it for now.

One gotcha I discovered right away is that the <a> tag does not allow the "target" attribute in XHTML Strict (nor does it in HTML Strict). However, the behavior of <a target="_blank"'> can be replicated in XHTML Strict with semantic markup and scripting.

Start by replacing the "target" attribute with the "rel" attribute:

<a href="url" rel="external">

Next, add a little bit of jQuery:

$(document).ready(function() {
    $("a[@rel='external']").addClass("external").
       .click(function() { window.open($(this).href); return false; });
});

This finds all anchor tags with rel="external" and causes them to open a new window when clicked. The "return false;" prevents the current page from switching to the URL as well. As an added benefit, these links get the CSS class "external" so they can be styled, perhaps with something like:

A.external {
  padding-left: 15px;
  background: url(external-link.png) top left no-repeat;
}

If JavaScript is not enabled, the link will behave as normal.