In some cases, you need to prevent users from opening links to external sites in the same window.

And what’s the easiest way to do that? jQuery, of course! Here’s my take on it:

jQuery(document).delegate(‘a’, ‘click’, function() {
	var root = location.href.replace(location.pathname + location.search + location.hash, '');

	if ( !this.href ) return;

	if ( 0 != this.href.indexOf(root) ) {
		window.open(this.href);
		return false;
	}
});

What’s going on up there? Let’s break it down:

jQuery(document).delegate(‘a’, ‘click’, function() {

First, we’re using event delegation to bind a click handler to any <a> tag.

var root = location.href.replace(location.pathname + location.search + location.hash, '');

Now we’re calculating the root address, based on the current location. For example:

http://localhost:8080/path/?foo=bar#baz

will become

http://localhost:8080

if ( !this.href ) return; is a safety check, for when there is no href attribute. this.href contains the absolute path for the clicked link.

if ( 0 != this.href.indexOf(root) ) {
	window.open(this.href);
	return false;
}

Finally, if the URL does not begin with the root we calculated before, it means it’s “external”. In this case, we open a new window / tab using window.open() and prevent the default action by returning false.

Update: Props to filosofo for pointing out that I should be using this.href instead of jQuery(this).attr('href').

Update 2: Use .delegate() instead of .live().