Open External Links as Blank Targets via Unobtrusive JavaScript

Beginning with this article, I am serving up a short series of unobtrusive JavaScript functions that I use to enhance the functionality of Perishable Press. In this post, I present a comprehensive JavaScript method of opening external links in new windows (or tabs, depending on the browser).

One way of opening links in new windows is to insert the HTML target="_blank" attribute into all necessary anchor elements (<a href=""></a>). This method works well, but generates validation errors when used with XHTML-Strict doctypes.

A better solution is to employ some unobtrusive JavaScript to progressively enhance your documents with “blank-target” functionality. Using the following code, 99% of your visitors (those with JavaScript) will enjoy external links opening in new windows, while the remaining 1% of your audience (those without JavaScript) will enjoy your site without even realizing they are missing out on those wonderful blank-targeted links. It’s a “win-win” situation ;)

To implement this unobtrusive, gracefully degradable strategy, simply replace any target="_blank" attributes with the XHTML-friendly rel="external" attribute. Using rel="external" is standards-compliant and thus completely valid, even for XHTML-Strict and XHTML-1.1 doctypes.

After you have prepared your external link anchors with rel="external" attributes, apply the following JavaScript either inline or externally. No additional editing or markup is required — grab, gulp, & go!

// Open External Links as Blank Targets via Unobtrusive JavaScript
// http://perishablepress.com/press/2007/11/20/open-external-links-as-blank-targets-via-unobtrusive-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.getAttribute("rel") == "external nofollow" || 
			anchor.getAttribute("rel") == "nofollow external" )
			)
		anchor.target = "_blank";
	}
}
window.onload = function() {
	externalLinks();
}

Other JavaScript methods 1 for opening external links in new windows work only if the rel attribute is set to external. However, in many situations, especially when working with WordPress and its myriad plugins, external links are also tagged with additional properties, such as nofollow, for example. The code presented in this article opens all links with any of the following attributes in a new window (click links for demo):

Of course, by modifying and/or emulating the sequence of anchor.getAttribute() expressions, it is relatively (no pun intended) straightforward to trigger blank-target behavior for virtually any rel attribute.

Footnotes

  • 1 This script has been adapted from the technique presented at Sitepoint.com