When opening new windows from your web page that link to external files, a common practice is to open them in a new window as not to deter the user from your site.
One method to do this in the past was to use target="_blank"
that tells the browser to open the link’s href
attribute in a new window. This, however, is deprecated in the Strict Doctype of W3C web standards so we should be trying to avoid using it whenever we can, and in this post I’ll show you exactly how it’s done.
Instead of using the target
attribute, we can use rel
to define the <a>
tags in our HTML that we want to open in a new page. Since these are usually external pages, we will use the external
keyword.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | Open a <a href="new-window.html" rel="external">New Window</a> with W3C valid syntax <script type="text/javascript"> var links = document.getElementsByTagName( 'a' ); for( var i = 0 ; i < links.length ; i++ ){ var rels = links[i].rel.split(' '); for( var j = 0 ; j < rels.length ; j++ ){ if( rels[j] == 'external' ){ links[i].onclick = function(){ window.open( this.href, '' ); return false; }; } } } </script> |
Line 1: This is where we give the link a rel
attribute
Lines 5-13: The script collects all <a>
tags and loops through them, splitting up each space separated term and checking if they equal “external
”
Lines 15-17: Sets the onclick
attribute of the link to allow window.open
to run and open a new window when the user clicks, containing the href
value.
Line 19: Returns false
to override the link’s default function, stopping it from opening a page of its own in the same window.
This can be run on any page that you have set your external links on and acts as a nicer, search-bot and standards friendly alternative.
jQuery Version
If your page is already using jQuery there is an even easier way to implement the code from above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Open a <a href="new-window.html" rel="external">New Window</a> with W3C valid syntax <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $( 'a[rel~=external]' ).click( function(){ window.open( this.href, '' ); return false; } ); </script> |
Much simpler.
I won’t go through the code on the jQuery example, but if you use the library, you should understand the selectors and methods I’ve used above.
The clever part is on line 7, where the selector finds all <a>
tags with a rel
attribute containing the “external
” keyword, even within a space-separated list of words.