Cast for two

Sunday, August 02, 2009

Set all links target to _blank on a XHTML 1.0 Strict using jquery

As explained here, opening links in a new window is no longer possible via target=_blank in XHTML 1.0 strict. This code is a workaround using 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;

A link with attribute rel set to external will open in a new window:

<a rel="external" href="http://castfortwo.blogpspot.com/">cast42</a>

On the Friendfeed realtime embed code, I saw they use jquery to do the job:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.js">
<script type="text/javascript">
$("body").mousedown(function(e) {
for (var target = e.target; target; target = target.parentNode) {
if (target.tagName == "A") {
if ((document.location.href.split("#")[0] + "#") == target.href) {
return;
}
target.target = "_blank";
return;
}
}
});
</script>

The advantage is that all links will open in a new window, except if the refere to an anchor in the page. Hence there's no need to add the attribute rel to each anchor.