External popup links using jQuery

A drawing of a cartoon man pointing upwards

Heads up! This post was written in 2007, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.

— Cory

With the deprecation of the target attribute in XHTML Strict, opening links in new windows has become a bit trivial, if not annoying, to standardize. I always look for a consistent, unobtrusive approach that degrades gracefully; and since I use jQuery quite frequently, this is how I usually handle them.

The solution is a small piece of jQuery code in your $(document).ready() section:

$(document).ready(function() {
  $(document).on('click', 'A[rel="external"]', function(event) {
    event.preventDefault();
    window.open($(this).attr('href'));
  });
});

Now, add rel="external" to all of the links that you want to open in a new window:

<a href="http://domain.com/" rel="external">Domain.com</a>

From here on out, users that have JavaScript enabled will receive external pages in new windows, while those without JavaScript will still be directed to the appropriate location.

I use rel="external" because it's generally a good practice to limit popup links to external websites only. You could very well use rel="popup" instead, but I prefer the former for semantics.