Link Targets, Web Standards, and jQuery

November 14th, 2008

As you may or may not be aware, XHTML 1.0 Strict does not include the old “target” attribute of a link. In other words, you can no longer code thusly in order to tell the client browser that you’d like the clicked link to open in a new window:

<a href="http://some.domain" target="_blank">Clicky!</a>

So what does one do if you still want to open a link in a new window while still maintaining the integrity of your XHTML document? There have been many proposed solutions to this, but they basically devolve to two basic theories: 1) Use javascript to make it work; and 2) Extend the DTD to reinclude the old target attribute. I tend to agree more with using javascript to make it work. Please don’t misunderstand. In an ideal world, extending the DTD would be awesome. Afterall, extensibility is part and partial to the whole XHTML idea. But in practice, I fear this would introduce too many interoperability issues between browsers.

So in order to open links in new windows you mark the tag as an “external” link using the rel tag, like this:

<a href="some.domain" rel="external">Clicky!</a>

Most articles I’ve read have been similar to the SitePoint article I linked to earlier, in that they use javascript like this to make any link tag with a rel attribute of “external” open in a new window:

<script type="text/javascript">
  function externalLinks() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) {
      var anchor = anchors[i];
      if (anchor.getAttribute("href") &&
        anchor.getAttribute("rel") == "external")
          anchor.target = "_blank";
    }
}
window.onload = externalLinks;
</script>

Enter jQuery. I’ve recently grown quite fond of this javascript framework. It’s elegant and powerful. While the above code is simple and straightforward, I’m already using jQuery, so why not just let it do the heavy lifting? We code it this way:

<script type="text/javascript">
  /* Reflects jQuery 1.3 syntax */
  $(function(){
    $("a[rel='external']").attr("target", "_blank");
  });
</script>

And in this manner, bliss is attained :-) Enjoy!

Leave a Reply