Open External Links as Blank Targets via Unobtrusive JavaScript

by Jeff Starr on Tuesday, November 20, 2007 22 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.

About the author

[ Jeff Starr ]

Jeff Starr is a web developer, graphic designer and content producer with over 10 years of experience and a passion for quality and detail. Jeff is co-author of the book Digging into WordPress and strives to help people be the best they can be on the Web. + Follow Jeff on Twitter and subscribe to Perishable Press for quality web-design content delivered fresh.


22 Responses

Add a comment

[ Gravatar Icon ]

Louis#1

“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 ?

[ Gravatar Icon ]

Perishable#2

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!

[ Gravatar Icon ]

Rick Beckman#3

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?

[ Gravatar Icon ]

Harrie Baken#4

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.

[ Gravatar Icon ]

Perishable#5

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 ;)

[ Gravatar Icon ]

Rick Beckman#6

Excellent. :)

[ Gravatar Icon ]

Perishable#7

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!

[ Gravatar Icon ]

Travis#8

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!

[ Gravatar Icon ]

Perishable#9

My pleasure! ;)

[ Gravatar Icon ]

Aaron#10

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!

[ Gravatar Icon ]

DinDin#11

Exelent idea, thanks!
But what if I want to give the new window specific size?
Is it possible?

[ Gravatar Icon ]

Erik Vold#12

Hey,

Nice script, I’ve made a little tweak, posted here: http://erikvold.com/blog/index.cfm/2008/12/3/open-external-links-as-blank-targets-via-unobtrusive-javascript-microformat-safe-version

I did two things:

1. I don’t make target=”_blank” if the target attribute already exists; for example say it was already target=”_parent”..

2. I use a reg exp to check for “external” in the rel tag, but this reg exp will not match “notexternal”, it would not match ‘xyz-external-123′, and a bunch of other unacceptable strings. This accounts for rel tag microformats.

Erik Vold

[ Gravatar Icon ]

Jeff Starr#13

@Erik Vold: That’s great! I tried getting the regular expression to match against attribute values containing additional terms (e.g., microformat tags) located either side of the “external” attribute value. I think it was the blank space throwing me off. Regardless, it is good to see an improved version of the script. I am sure it will benefit the community. Thank you for the work, and thanks for sharing it with us. :)

[ Gravatar Icon ]

Adieska#14

Where did we put those JavaScript code in our blog?

[ Gravatar Icon ]

Jeff Starr#15

@Adieska: The simplest way is to place the code in the <head> section of your web page(s), like this:

<script type="text/javascript">
<!--//--><![CDATA[//><!--

JavaScript goes here
JavaScript goes here

//--><!]]>
</script>

Alternately, you can place the code into an external JavaScript file (named something like, “javascript.js”) and then link to the file in the <head> (or footer) section of your web page(s).

[ Gravatar Icon ]

Adieska#16

Thanks my bro. It works :D

[ Gravatar Icon ]

Praveen#17

Good. Here, is an interesting post which discuss the same, along with how to open only specific content links in new window.
http://praveenbattula.blogspot…..indow.html

Trackbacks / Pingbacks
  1. Offsite links, the Browser and the User | Yillb.com
  2. Blodhemn ! | Target="_blank" problem and my 3 questions
  3. target=”_blank”を使わずに、rel=”external”、rel=”external nofollow”で新しいウィンドウを開く方法 | 清音のSEOブログ
  4. Changing Doctype of Thesis-Theme - DIYthemes Forums
  5. ゆっくりと… » WordPressテーマinoveのRSSリーダー登録メニューを日本向けに変える
Share your thoughts..

Read Comment Policy

Comment Rules: No spam. No profanity. Use your real name. You may use simple HTML tags for style. Wrap all code in <code> tags. Learn more.



Attention: Do NOT follow this link!