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

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:

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.

Comments

blog comments powered by Disqus