Use 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:
- Use base target to target links instead of using Javascript (Thursday, September 22nd 2011)
- Target links to _top with jQuery (Wednesday, July 21st 2010)
- jQuery: set title of anchor tags to the href for offsite links (Tuesday, July 6th 2010)
- Add an offsite link icon after external links with jQuery (Saturday, March 28th 2009)
- jQuery's document ready initialization (Friday, February 20th 2009)
- Loading content with jQuery AJAX (Wednesday, January 14th 2009)

Comments
blog comments powered by Disqus