Article

New-Window Links in a Standards-Compliant World

Page: 1 2 3

A Fine Line

As a bit of a perfectionist, my first impulse when I learned of this solution was to ask, "Is there really a difference?" And yes, I often talk to myself while doing research.

I mean, if the target attribute of the <a> tag is being phased out, does it really make a difference whether we're setting it with JavaScript instead of HTML? Sure, the page will validate against the HTML 4.0 Strict and XHTML 1.0 Strict Document Type Definitions, but aren't we technically cheating?

The answer is no. The Document Object Model (DOM), which governs the document objects and attributes that are available to JavaScript code, is a totally separate standard from (X)HTML. Also consider that the DOM 2.0 standard that was published in January 2003 (well after XHTML 1.0, let alone HTML 4.0) still includes this attribute. It seems clear that while this attribute is slated to be phased out of (X)HTML, it will be available to JavaScript through the DOM for the foreseeable future.

A number of other standards-compliant new-window link scripts out there propose using window.open() to load the document in a new window. While this approach generally works well on the surface, its downfall is that most browsers do not correctly report the referring URL in the request for the new page, which can be a serious issue, especially in inter-site links.

The Complete Script

As promised, here is the complete script. Notice the last line, which assigns the externalLinks function to the window's onload event handler. This triggers the function when the document has finished loading.

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.target = "_blank";  
 }  
}  
window.onload = externalLinks;

As this is the kind of script you'll want to deploy across your entire site, you should copy this code into a separate file (e.g. external.js), and then load it in every page on your site with the following code, which should appear in the <head> tag of each document:

<script type="text/javascript" src="/external.js">  
</script>

Problem solved!

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: