XHTML compliant external links
Wednesday 1 October 2008I’m a fan of the clean semantic markup of XHTML 1.0, but find it very annoying that you can’t use the old target=”_blank” on anchors to open in a new window.
However, I did stumble upon this very nice solution:
<a href=”www.awebsite.com” title=”Some website” rel=”external”>some external website</a>
Now, on it’s own that’s just a normal link with the ‘rel’ attribute added, but with the aid of some 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;
…the somewhat semantic (and xhtml valid) markup of rel=”external” is replaced by target=”_blank” on the fly. Some may call this cheating, but I can see no problem with using this solution should you require a link to open in a new window. Always avoid overusing new windows however, it can be very annoying!
Thanks to Kevin Yank and this article for the solution.
