XHTML Strict target resolved with jQuery

This post has been updated. Please also see Replacing target=”_blank” for Strict XHTML using JQuery (redux)

All good web developers now design sites using the XHTML Strict DTD. Strict XHTML forbids the use of the target="_blank" attribute on anchors, used to open a link in anew browser window. The reason for this is that there should be a separation between presentation and behaviour.

This is all fine and dandy until your customer requests that all links to external sites open in a new browser window. This is not an unreasonable request.

The answer is to add an an event to such links using Javascript. As a fan of jQuery, this could not be easier.

Step 1. Add a rel attribute to all external links/anchors

e.g.

<a href="externalsite.com" rel="external" />

Step 2. Include the following jQuery script

$('a[rel=external]').attr('target', '_blank');

If adding the target attribute seems like a hack, then the following should achieve the same goal

$('a[rel=external]').click(function(){window.open(this.href);
return false;

This may all seem a bit obvious, but I’m sure there’s someone out there looking for an elegant fix like this.

Tags: ,

5 Comments

Karl Swedberg commented on October 25th, 2008 at 4:35 am

“All good web developers now design sites using the XHTML Strict DTD.”
That’s a gross overstatement. Consider these two “good” web developers, for example: Roger Johansson and Ian Hickson. Perhaps a more fair claim would be “most good web developers now design sites using a strict DTD.”

cobasa commented on January 17th, 2009 at 5:54 pm

very nice.
also i think you need an exact number for developers who use xhtml strict, a list of all good web developers, and a definition of “good” and “developers” translated into klingon (just in case).

Jaako commented on March 1st, 2009 at 5:24 am

Thanks for sharing,

However, this breaks on links with other information in the rel=”" attribute (such as rel=”nofollow”)

rel=”nofollow external” is no good.

[...] first solution I came across used jQuery to find external links with the rel="external" attribute and add a [...]

Erik commented on January 29th, 2010 at 7:09 am

This little snippet saved my bacon. Awesome, awesome work. Thanks for sharing.

Leave a Reply

CAPTCHA Image

Colophon

badlyDrawnToy is the blog of Howie Weiner, a knackered, old web developer, based in Manchester.

Howie is Technical Director at JP74 and specialises in PHP (Kohana) and Java (Spring) web applications, Search Engine Optimisation, custom CMS and web development.

View Howie Weiner's profile on LinkedIn
View Howie's twitter feed