Links in a new window, 2008-style

The first thing you learn as a web developer is probably how to make a link. It’s so basic to the web that it is hard to see what’s wrong with it. Still, some people think the good old A tag needs a stern talking-to. Especially in the area of behaviour.

You see, vanilla links are fine. These open in the same browser window. But ever since the introduction of XHTML 1.0 Strict there has been discussion about links that open in a new window. This is deemed “behaviour” and thus had to be separated from the markup.

I do not nessesarily agree with this. “Link in a new window” is such an overwhelmingly basic aspect of building a link I think it does belong in the markup. But who am I.

You normally indicate new-window-ness with the target attribute:

Example

This is not permitted in XHTML 1.0 Strict. So, without agreeing to this standard, there it is, invalidating our sites! What to do? Simple; we add the behaviour required through the use of Javascript. On the one hand, makes sense. It’s good to separate these two. On the other hand, it a lotta extra work, convoluted code and it feels so …. pointless.

Now that I am using jQuery exclusively there really is no reason not to do this though. jQuery makes it so simple.

One of the most popular ways to add new-window-behaviour to links is via the rel=external attribute. So let’s use that, which makes our links into this:

Example

Now to add a bit of javascript magic I use the jQuery library.

If you are still writing javascript by hand, you are insane. You can get ten times the work done in half the time and in such a way that it works on all browsers all the time. Stop coding javascript by hand you moron!

There are several ways posted online (some with surprising high Google ranking) but here is the best one. It’s as concise as possible while still fool proof.

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

I’ve seen “solutions” that add to the click event for links, which is convoluted. There is nothing intrinsically wrong with the target attribute, it just isn’t allowed for this particular doctype. So we’re using it, which also prevents any popup blockery.

We really need to wrap this inside a document.ready though. We are going to have to wait for jQuery to load and also for the entire DOM to be available. If you don’t do this, chances are you are calling it too soon and the call cannot find any elements.