jQuery: Open External Links In New Window/Tab
18 May 2009
The common technique to force links to open a new window or tab is to add a target
attribute like so:
<a href="http://hulu.com" target="_blank">check it out</a>
This works just fine but is not actually valid markup. Fortunately, we can use jQuery to add the target attribute so it doesn’t muck up the HTML.
$(document).ready(function() {
$('a[rel="external"]').click(function(){
$(this).attr('target','_blank');
});
});
Change that invalid link to look like this instead:
<a href="http://hulu.com" rel="external">check it out</a>
Now the link forces browsers to open a new window/tab and the markup is still valid. Easy cheesy.