It’s easy to overlook the basics sometimes and be a clever dick with some overly complicated Javascript solution when there’s a nice easy HTML attribute that can solve the problem. In this post, I’m talking about the target attribute of the <base> tag which I suddenly had an "ohhhhh" moment with yesterday. There’s no need to use jQuery/Javascript to target links to _top, for example, just set the target in the base tag.
Why bother setting the target at all?
If you have content in an <iframe> with links in it, they will be default target the same iframe. You may want them to target a blank window/tab or the parent window.
Why not just set it in the <a> tag?
Well yes, you could just set the target in all the <a> tags on your pages too, but in my case there’s already a lot of existing content in many pages and I don’t want to have to go through all of them and update them / do a database query to update them.
And anyway, it’s easier to set a default (e.g. _top) and then set something different for specific links should you need to.
How to do it then?
If you want to target all links by default to _top, for example, then add this to the <head> section of your HTML document/template:
<base target="_top" />
Then for any links you want to target elsewhere, add a target for them:
<a href="something.html" target="_blank">
But isn’t the target attribute deprecated?
It was, but now it’s not. The W3C deprecated the target attribute for links etc some time back for reasons I’ve never been able to understand; they supported the <iframe> element but deprecated the attributed that allowed targeting into and out of it…
In HTML5, they’ve un-deprecated it and added it to the <base> element too. Fortunately older pre-HTML5 browsers appear to all support the attribute in <base> anyway; I’ve tried it in a combination of old and new browsers (FF3.0, FF6.0, IE6, IE9 and Chrome) with no issues.