Opening links in a new window with jQuery

With the advent of XHTML Strict 1, you can no longer use target=”_blank” on an A tag in your code. The only solution for this is to use Javascript to action a new window / tab to be opened.

The traditional way would be something this:

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
27
// externalLinks()
/*
* Allows external links to be opened in a new window without the use of target attribute
* @return bool
*/
function externalLinks() {
//SETS DOMAIN OF SITE
var domainName=document.domain;
 
var externalLinks=document.getElementsByTagName("a"); //FIND ALL LINKS ON THE CURRENT PAGE
 
for(var i=0; i<externallinks .length; i++) { //LOOP THROUGH LINKS ARRAY
	var attribute=externalLinks[i].getAttribute("href"); //GETS CONTENT OF 'HREF' ATTRIBUTE ON CLICKED LINK
	var elementClass = externalLinks[i].className; //STORES CLASS NAME OF ELEMENT
	var contains_http=attribute.indexOf("http"); //GET VALUE http IN 'HREF' **FOR MOZILLA&&
	var contains_domain=attribute.indexOf(domainName); //GET VALUE domainName **FOR IE**
	if(newWindowLink == true) {
		if(contains_http>-1 && contains_domain==-1) { //DOES CONTAIN AN 'http' OR DOES NOT CONTAIN domainName
			setElementAttribute(externalLinks[i], 'target', '_blank');	
		}
	}
 
	if(elementClass.indexOf('new_window') > -1 ) { //FORCE LINK TO OPEN IN NEW WINDOW
		setElementAttribute(externalLinks[i], 'target', '_blank');
	}		
}
}</externallinks>

This was written by Mike van Rooyen at 9xb.

A much simpler way of doing this comes with jQuery, and can be reduced down to one line.

1
$("a[href^=http://]").attr("target", "_blank");

Mike’s solution also makes sure that it doesn’t apply this to links to your own site, which is useful for sites running frameworks like WordPress – where links are embedded absolutely.

Therefore, something like this might be a little more suited.

1
2
3
4
5
$("a[href^=http://]").each(function(){
	if(!$(this).attr('href').indexOf(document.domain)){
		$(this).attr("target", "_blank");
	}
});