Written by Michael Lankton Tuesday, 22 September 2009 19:59
Face it, the average web user isn't too savvy. One click and they've forgotten about you forever, maybe before they saw the content you wanted them to see in the first place. You only get one chance to make a first impression.
In the past, we've always used the "target" attribute of the <a> element to specify how we want external links to open. For external links, many of us like to use target="_blank", which opens the link in a new browser window. The problem is, the target attribute is deprecated, so going forward with strict and HTML 5 markup, it isn't valid code.
What's the solution? Just treat external links like internal links and say goodbye to all those people who surfed in on Google, because they'll be gone in a click?
Not to worry. There is a valid way to keep your external links opening in new windows. To do it, we need to use javascript. Don't get all scared, I am going to supply a sample script and tell you how to implement it.
We can't use the "blank" attribute anymore in HTML, but it's perfectly valid javascript. Thanks to Kevin Yank, whose article steered me in the right direction. The only thing I changed about his example was to add an ELSE IF to the script to allow for both dofollow and nofollow links.
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 nofollow")
anchor.target = "_blank";
else if (anchor.getAttribute("href") &&
anchor.getAttribute("rel") == "external")
anchor.target = "_blank";
}
}
window.onload = externalLinks;
Feel free to use the above javascript as is, or use it as an example to write your own. Save it as whatever .js, and then just add it to your <head> by calling it thus:
<script type="text/javascript" src="/path/to/script/external_links.js"></script> />
Now you have the ability to have both dofollow and nofollow external links open in a new window. All you need to do is add the rel attribute to your <a> element and specify:
Nofollow:
rel="external nofollow"
Dofollow:
rel="external"
It's as simple as that, and it produces valid strict and HTML 5 markup.


