Web Development with PHP, HTML, CSS, & JavaScript

Opening a new window with Unobtrusive Javascript

Sunday 8th November 2009

According to the W3C Specifications, XHTML should only deal with information displayed in a browser window. Basically, opening a new window is something that does not relate to the current window, and therefore XHTML should not perform this action. So, when opening a new page, this should be opening in the same browser window. If we want to open a new window, this is not the responsibility of the XHTML (information, data) but rather should be handled by javascript (behaviour).

After reading an article on New-Window Links in a Standards-Compliant World by Kevin Yank a few years back, I adopted the practice of no longer using the target='_blank' attribute, in order for my websites to validate. But I still wanted the ability to open links in a new window in an unobtrusive and accessible way. So I started using a small and useful script, external.js.

<!--Old, deprecated html:-->
<a href=" " target='_blank'>external link</a>

<!--New html:-->
<a href="" rel="external">external link</a>

External.js uses the rel attribute of links to specify which links should be opened in a new window. If you have a link on your website with rel="external", external.js will open this link in a new window. If not, the link will open in the same window as usual. To include the external.js in your html, just save the javascript file on your server, and link to it in the <head> of your document as so:

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

An issue with using this is that the the rel attribute has a number of pre-defined standard values, of which "external" is not one. But the rel attribute is intended to specify the relationship between the document that contains the link, and the target of the link. And it is allowed to take any value, even a space separated string. So you can use rel="external" and your code will still validate. Also, the value "external" does help to specify the relationship between the document and the links target, in most cases where it is used.

Along with the fact that it is a small and useful piece of javascript that keeps my html valid, it is also a gracefully degrading solution. If a user has no javascript or has javascript turned off, the link will not open in a new browser window, but the link itself will still work.