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
if ( !this.href ) return;
This 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().

You should use `delegate` in jQuery. It’s pretty faster than `live`. So the code will be:
jQuery(‘#wrapper’).delegate(‘a’, ‘click’, function() {
You may need to change `wrapper` according to your needs ;)
Yep, updated tutorial. :)
This doesn’t work for me, I’m not getting the links to open in a new window. Using Safari on the Mac.
another way:
$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])").attr("target","_blank");
scribu you have error in your code…
there should bre window.open(this.href); instead of window.open(url);
Thanks. Corrected.
As of jQuery 1.7 .delegate() is superseded by .on().