Use jQuery to make all offsite links open in a new window
Posted March 24th, 2009 in Javascript
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.
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. Friday's post will show how to add one of those offsite link images after the link with jQuery.
Related posts:
- 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)
- Dynamically get and set an elements content with jQuery (Sunday, January 11th 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

