Spring Sale! Save 30% on all books w/ code: PLANET24
Web Dev + WordPress + Security

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

Blank Targets

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. Here is an example for those who may be unfamiliar with the good ’ol blank-target attribute:

<a target="_blank" href="https://m0n.co/">Opens in new tab</a>

JavaScript Way

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
// https://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 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.

About the Author
Jeff Starr = Web Developer. Book Author. Secretly Important.
GA Pro: Add Google Analytics to WordPress like a pro.

23 responses to “Open External Links as Blank Targets via Unobtrusive JavaScript”

  1. Jeff Starr 2008/12/03 6:00 pm

    @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. :)

  2. Where did we put those JavaScript code in our blog?

  3. Jeff Starr 2009/01/03 6:30 pm

    @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).

  4. Thanks my bro. It works :D

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

  6. If you already have another existing script with a window.onload = function() call, you’ll need to add the externalLinks() call to that window.onload call.

  7. Hello everybody.

    I would like to adapt this to open a “form” in a new window, but a form doesn’t have a “href” anchor. Do you know how i could do this ?

    The form is used to pass some parameters to an URL an= the open that URL in a new window. The usual ‘ works perfect, but is no W3C compliant.

    Thanks.

  8. This code is brilliant!

    This is the only way for Drupal 6. I tried many other scripts and they doesn’t work. Great job!

  9. meelijane 2012/05/03 9:48 pm

    @greyliar, there’s a module called ‘external links’ that works just fine.

  10. what if i don’t have rel="..." ?

  11. Thanks for this!
    outline: 0; /* stops the outline on the page over a link! */

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
GA Pro: Add Google Analytics to WordPress like a pro.
Thoughts
I live right next door to the absolute loudest car in town. And the owner loves to drive it.
8G Firewall now out of beta testing, ready for use on production sites.
It's all about that ad revenue baby.
Note to self: encrypting 500 GB of data on my iMac takes around 8 hours.
Getting back into things after a bit of a break. Currently 7° F outside. Chillz.
2024 is going to make 2020 look like a vacation. Prepare accordingly.
First snow of the year :)
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.