Javascript logo

xhtml external links

home | software | javascripts | xhtml external links

For a while, I was striving to keep my markup compliant with the XHTML-strict specification. Specifically, I wanted the W3C Validator to pass my pages (nowadays I'm aiming for HTML5 compliance.)

However at times this can be frustrating, especially if you're used to how browsers worked at the turn of the century.

One difficulty I faced involved forcing external pages to launch in their own window (or tab for Mozilla users). XHTML strict, in fact no strict HTML specification has ever included the 'target' attribute for anchor elements. Instead, we're advised to use window.open(...); javascript. This can be quite verbose. Hey presto, Javascript to the rescue...

Instead of this code:

<a href="http://site.com" target="_blank" onclick="window.open('http://site.com'); return false;" onkeypress="window.open('http://site.com'); return false;">some site</a>

Use this much more concise code:

<a href="http://site.com" rel="external">some site</a>

Of course you'll also need to import the javascript file, which you can do in the head section of your HTML document:

<script src="xhtml-external-links.js" type="text/javascript"></script>

The xhtml-external-links.js scans all links in your document and attaches it's own event handler to open the link in a new window if the external value is contained within the rel attribute. Note that other values (such as nofollow) may exist (such as nofollow) as the rel attribute is defined as a space separated list.

the code

xhtml-external-links.js - right-click and choose save as