Use jQuery to make all offsite links open in a new windowUse jQuery to make all offsite links open in a new window

Posted March 24th, 2009 in Javascript (Updated September 23rd, 2011)

XHTML Strict does not allow opening links in a new window using target="_blank" so instead you can use jQuery to add the target attribute to all <a> tags after the page has loaded and still have the page validate as XHTML strict. (But refer to my updated note at the end of the article regarding the base tag and the un-deprecation of the target attribute).

jQuery Code

Simply add the following piece of code into your $(document).ready(function() { } section of code (more about that in my jQuery's document ready initialization post):

$("a").filter(function() {
    return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');

What this does is to add target='_blank' to all <a> tags in the current webpage that do not link to the domain you are currently on.

Therefore on my blog, applying the jQuery code above would make the following open in the same window:

<a href="/jquery-open-offsite-links-new-window/"> ... </a>
<a href="http://www.electrictoolbox.com/jquery-open-offsite-links-new-window/"> ... </a>

and the following in a new window:

<a href="http://www.google.com"> ... </a>
<a href="http://www.yahoo.com"> ... </a>

It's then possible to replace attr() with other functions to do things to external links on a page. The next post shows how to add one of those offsite link images after the link with jQuery.

Update September 23rd 2011

With HTML5, the W3C has un-deprecated the target attribute so you can add target attributes to <a> and <form> tags and have the document still validate. Using jQuery as shown above can still be useful if you have a lot of pages and don't wish to have to manually update all the links.

Related posts:

Comments

blog comments powered by Disqus