ieatpenguin

September 30, 2009

Emulating target=”_blank” in XHTML

Filed under: Javascript — Russell @ 3:00 pm

A friend was having trouble with this earlier today so thought I’d post the answer. Whether or not you consider this cheating (I don’t), it’s the only way to get a link to open in a new window and remain valid XHTML code, and be valid in the upcoming XHTML 4.0. It is still valid in XHTML 1.0.

The reason this was taken out in XHTML 4.0, is that the W3 see a new window as no longer being the concern of the current document – and so not valid XHTML, as therein lies the language’s concern.

Anyway, to the solution, a simple bit of Javascript:

function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}
window.onload = externalLinks;

Place this in a .js file along with the rest of your .html files, and then call it in the head of the document thus:

<script type="text/javascript" src="xhtmllinks.js"></script>

And then edit your links to call the script every time they are clicked:

<a href="http://www.r-dunn.co.uk/ieatpenguin/" rel="external">i eat penguin</a>

If you enjoyed this post, make sure you subscribe to my RSS feed!

3 Comments »

  1. target=”_blank” still works in XHTML 1.0 (4.0 isn’t out), but it’s not strict valid. Validates transitional, though :)

    Comment by Jasper — September 30, 2009 @ 6:50 pm

  2. Aye you’re absolutely right, not intending to be mis-leading in any way :) .

    I suppose for most people transitional will be enough for a fairly long time to come.

    Comment by Russell — October 1, 2009 @ 9:27 am

  3. This is exciting.

    Comment by alistairparr — October 1, 2009 @ 9:32 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

You must be logged in to post a comment.

Powered by WordPress