tag. However the latest HTML standards no longer include the "target" attribute." /> MattsBits - Standards Compliant Opening HTML Links In A New Window
MattsBits
MattsBits

MattsBits

Standards Compliant Opening HTML Links In A New Window  

by Matt Hawkins, 16/09/2010
Categories : HTML & CSS

The simpliest way to open an HTML link in a new windows is to make use of the "target" attribute within the <a> tag.

<a href="http://www.mattsbits.co.uk/" target="_blank">Link</a>


However the HTML 4.0 Strict and XHTML 1.0 Strict standards no longer include the "target" attribute.

So what can you use instead?

The new standards removed the "target" attribute but added a "rel" attribute. This attribute is meant to describe the relationship between the page containing the link and the page pointed to by the link.

So your links can be created as :

<a href="http://www.mattsbits.co.uk/" rel="external">Link</a>

This link is now standards compliant but it requires a block of Javscript in order to actually launch the link in a new window.

The following script should be included in the <head> section of your page :


/*---------------------------------------------------*/
/* mattsbits.co.uk */
/* */
/* This function allows certain links to open in a */
/* new window. Those links have a rel attribute set */
/* to "external". */
/*---------------------------------------------------*/
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;


It can be included in an external js file (eg js_external.js and included by putting the following entry into your <head> section :

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


The script looks for all <a> tags on the page with rel attributes set to "external". It then sets the link target to "_blank". This gives the user the same functionality as using target="_blank" but keeping the source of the page standards compliant.

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2022