Open External Links in a New Window Using jQuery

Jocelyn's picture

The way people have typically opened external links in a new window is to use the attribute target="_blank" in an <a> tag. The problem is that in HTML/XHTML Strict, the target attribute is deprecated.

While you can still use the target attribute if you're using the Transitional DOCTYPE, best practice is to adhere to web standards.

The Problem

<a href="http://monkey.com" title="monkey" target="_blank">monkey</a>
<a href="http://monkey.com" title="monkey" rel="external">monkey</a>

The Solution

$(document).ready(function() {
  $('a[href^="http"]').not('[href*="mysite.com"]').attr('target', '_blank');
}

What the above translates to is:

  • when the page is loaded
  • check all the <a> tags that start with http
  • and do not contain my url
  • add target="_blank"

At first this may seem like a bunch of extra code that's doing the same thing as just specifying the target attribute in the first place. But since jQuery is rendered client-side, while the structure of your document is standards-compliant, you get the desired effect of opening external links a new window. Should someone have JavaScript disabled, your links will behave as normal.

If you do a comparison of a view source of your page and compare that with an Inspect Element with Firebug you'll see the difference.

Choosing a DOCTYPE

A Transitional DOCTYPE may be used when you have a lot of legacy markup that cannot easily be converted to comply with a Strict DOCTYPE. But Strict is what you should be aiming for.

From Roger Johansson's article Transitional vs Strict Markup

Add New Comment