Open External Links as Blank Targets via Unobtrusive JavaScript

Published Tuesday, November 20, 2007 @ 10:05 am • 11 Responses

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 here.

Dialogue

11 Responses Jump to comment form

1Louis

November 20, 2007 at 1:50 pm

“Open External Links as Blank Targets”

It just feel so wrong !

I can’t believe you advice us to use target=_blank links. It’s been highly debated that no one should force the user’s browser to behave differently.

If a user wants to open a link in another tab, then he justs ask for it, by middle-clicking or by another way. It’s a very bad thing to impose him to open a new page (yes, in Safari, target=_blank does not create a new tab, but a new windows, even with tabs on)

Aren’t you upset when a link does not behave as intended ?

2Perishable

November 20, 2007 at 2:12 pm

Well now, everybody just calm down..

This article is meant for informational purposes only. The information and techniques presented here are intended to serve a particular need, not to advise or advocate any particular method of doing anything. If you re-read through the article, you will see that I never advise, only explain. I leave it up to the reader to decide whether it is necessary or not.

You bring up a good point, though. Visitors should have control and be given the option of opening links in new windows or tabs. However, there are certain situations in which providing external links fosters usability and accessibility. For example, one of the few types of links that I like to have opened automatically in a new window are “theme-demonstration” links. Changing the WP theme requires cookies, alters the entire layout, and resets the page to the blog root. Unsuspecting visitors would be left dazed and confused with a single click if such links weren’t opened in a new window.

What’s really crazy is that I care enough about web standards to even bother with an entire script for this purpose. Believe me, it would have been far easier to just take the lazy way out and slip in a few target="_blank" attributes here and there. After all, it’s only like four or five pages on the entire site that even use them!

3Rick Beckman

November 20, 2007 at 2:48 pm

Perishable: What if an external link uses XFN as well? For instance, its REL attribute may be equal to “external coworker” or “external sweetheart met.”

Would the “or equals” method work in such cases, or would the JavaScript need to be changed to look for “external” among any number of possible REL entries?

4Harrie Baken

November 20, 2007 at 3:50 pm

I think the script is just great. Writing XHTML Strict, I still want that for the sake of (many?) visitors some files open in a new window or tab. E.g. pdf and spreadsheets.

5Perishable

November 20, 2007 at 5:08 pm

Excellent point, Rick. Rather than writing out every possible rel attribute, we can use a regular expression to match virtually any instances of external. A few additional variables, including one for the regular expression, and we have something like:

// match all instances of 'external'
function externalLinks() {
     if (!document.getElementsByTagName) return;
     var anchors = document.getElementsByTagName("a");
     for (var i=0; i<anchors.length; i++) {
          var relative = anchor.getAttribute("rel");
          var pattern = /external/i;
          var anchor = anchors[i];
          if (anchor.getAttribute("href") && external.test(relative)) {
               anchor.target = "_blank";
          }
     }
}

Also, notice the “i” after the regex (i.e., /external/i). This renders the string case-insensitive, providing a greater match sensitivity. Definitely no need for extraneous “or equals” statements. Thanks for the subtle reminder, btw ;)

6Rick Beckman

November 20, 2007 at 5:14 pm

Excellent. :)

7Perishable

November 20, 2007 at 5:17 pm

Harrie,

You are absolutely correct, there are many genuinely valid reasons for employing externally opening web documents. In addition to the excellent examples you mention, there are also peripheral resources such as images, movies, and other multimedia content that definitely warrant their own window or tab. I agree that such functionality helps a majority of visitors. Thanks for the comment!

8Travis

November 26, 2007 at 4:43 pm

That’s a great little piece Perishable - to add my voice to the chorus, there are definitely times when you want a document to open in a new window.

Thanks for the idea!

9Perishable

November 26, 2007 at 9:13 pm

My pleasure! ;)

10Aaron

July 12, 2008 at 4:38 pm

This is great code but I was looking for a wordpress plugin. I figure others will find this who want a wordpress plugin so here’s what I found: http://wordpress.org/extend/plugins/blank-target-replacement/ The code may need to be tweaked to work like comment number five buts it’s easier than starting from scratch. Thanks!

Subscribe to comments on this post


Share your thoughts..

TopRead official comment policy

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

mmmm, dark chocolate..

Perishable on Tumblr

Tons of Firewalls

Tuesday, 7 October 2008, 1:45 am

Recently overheard on conservative talk radio (instructing listeners how to obtain a free promotional video from their new website):

“This website has tons and tons of firewalls, so you have to use your real email address to download the video..”

The Quiet Search Revolution

Monday, 6 October 2008, 12:15 pm

Just a thought.. As awesome as Google is these days, it would suck if they ended up owning the entire search-engine business. When they get to the point where all competition is impossible (due to their sheer size, financial resources, media influence, etc.), how many alternate search engines will have the resources for continuous improvement and top-quality search results? When this happens, we will have no choice but to do exactly what Google tells us to do.

As deeply ingrained as it is for everyone to instinctively and unthinkingly turn to Google for their search activity, it is time to leave a few alternate search tabs open for as much use as possible. Instead of using Google just because that’s what you always do, try your search on MSN, Yahoo, Ask, or any of the other independent search engines instead. Sharing traffic with other search engines is a nice, quiet way to keep the competitive spirit alive and well in the search-engine business.

Disappearing WordPress Posts

Wednesday, 1 October 2008, 7:50 pm

Today I experienced difficulties while trying to publish or even save new posts in WordPress. I would compose the post as usual, add all of the keywords, tags, meta tags, and so on, but as soon as I clicked the “Publish” or “Save” button, the post would just disappear from existence.

The weird thing is that during the drafting process, WordPress’ default auto-save feature showed that the post had been saved at expected intervals. Unfortunately, after trying to publish several different posts, WordPress showed absolutely no record of the posts ever being created. They simply vanished into thin air.

Fortunately, a little investigation revealed the culprit. If you should find yourself dealing with this same issue, here are some different things that you should try. First, re-upload fresh copies of your entire WordPress installation. I don’t know why exactly, but apparently various files can either go stale or completely disappear from the server. Overwriting or writing fresh files may do the trick.

If that doesn’t work, check your WordPress database for errors. In my case, a little investigation revealed that something had caused a couple of fatal errors in the wp_posts table. Fortunately, checking and repairing the table solved the issue.

Tumblr Battles

Wednesday, 1 October 2008, 5:30 pm

Please excuse the duplicate Tumbr posts.. seems there is no way to ping Tumblr to refresh/rebuild the RSS feed according to changes in post content. So, to resolve the issue I have discussed now like two or three times regarding paragraph elements and proper feed formatting, I have no choice but to repost a majority of my text posts.

This is necessary for the proper import and display of my Tumblr feed into WordPress. Currently, there are five items displayed at once, each styled according to proper inclusion of paragraph tags. Thus, whenever the Tumblr feed “forgets” to enclose single-paragraph posts with the proper tags, the result is an unstyled post entry displayed on my site.

Assuming that makes sense, you will please excuse my dust while I repost a few older entries in an attempt to reconstruct (the hard way) a properly formatted Tumblr feed.

More Optimization Measures

Wednesday, 1 October 2008, 5:27 pm

Another important step in improving the performance of my recent redesign involves the optimization of both CSS and JavaScript content. During development there were around 15 server requests for these two types of files, 10 JavaScript files and 5 CSS files. This was okay for my own use, but would not work for production purposes.

Optimizing these file types involves consolidation, compression, and caching. Consolidation of 10 JavaScript files into three is huge improvement. Now I deliver one JS file for the functionality of the site, one for Mint, and another for Analytics. Likewise for the stylesheets; after consolidation, a single stylesheet is delivered to all modern browsers. There are two additional stylesheets as well, but they are targeted at IE6 and mobile browsers and will not load elsewhere.

Once the files were consolidated as much as possible, it was time to optimize or “crunch” them. Using the sexy Flumpcakes CSS optimizer, I was able to reduce my stylesheets by around 25%. Likewise for JavaScript, I used xtreeme.com’s optimizer to shave an additional 20% off the size of my JS content.

Finally, once I had consolidated and compressed my JS and CSS files as much as possible, I wanted to further my optimization efforts by ensuring that these files were cached by the browser. By setting far-future Expires headers for everything but the statistical files, my site gains an additional performance boost by eliminating the need to reload preexisting content.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Nyx: Happy to have helped! Love your site....
  • dockside: Hi i want to use this code on my blog. but not for all post. I want 3 or 4 full posts and then post in double column How?...
  • NZ Beats: Got it working using the following: http://www.nzbeats.com/?feed=rss2&category_name=album-review...
  • Paul: Holy crap, you just saved my A$$! Thank you!...
  • free games: Google have a content distribution network here http://code.google.com/apis/ajaxlibs/documentation/#AjaxLibraries where you ca...
  • free games: Found this (untested) for those that just want https For HTTPS: var pageTracker = _gat._getTracker("UA-XXXX-1"); pageTracker...
  • H5N1: The question is very hard. No way to solve it in only few words :) First of all you need a Linux. OK. But Linux it's only a Kerne...
  • gowers: wow, your theme is so great, I like it...
  • Eric Ferraiuolo: Like some people are commenting, a virtual solution is going to be the easiest to get going with the least number of issues. I would ...
  • Brent Terrazas: Thanks for the mention, I currently am running Ubuntu Server 8.04 on VMWare Fusion beta (it's a free beta download.. check it out fo...

Read more recent comments..