Blankfield.net

Website Design » Web Application Development » Photography

XHTML-Valid External Links using jQuery

0 Comments Thursday, June 24th, 2010.

You’re probably aware that the target attribute was removed from the XHTML specification way back when. This is mainly due to the rule that we as web developers should all be following: the browser belongs to the user (read: I’ll decide if and when I want another window or tab to open, thank you very much). However, there are times you may find it necessary or in the user’s interest to have a new tab or window open.

Note: As of the current draft, the target attribute has been de-deprecated in HTML5.

If you are looking to remove those deprecated target="_blank" attributes from your links, it’s very easy to do with jQuery. Here is one of the more concise bits of code used to open an external link in a new tab or window using jQuery:

$("a[rel='external']").click(function(){this.attr("target","_blank");});

OR

$("a[rel='external']").each(function(i){$(this).attr("target","_blank");});

(Of course, with these you’ll need to add rel="external" to any <a> tags that you wish to use them on.)

If you would like all links to other sites to open in a new window automatically, here is an even more succinct instruction. (props to Roger):


("a[href^='http:']").not("[href*='mydomain.com']").attr('target','_blank');
// swap out “mydomain.com” with your domain name

Personally, I don’t recommend using this blanket method, as I typically don’t like it when new tabs open without my consent; save new windows or tabs for just the right situation. Heck, that’s why Apple invented the Command key.

Leave a comment!