Use this snippet to make external links on a page open in a new tab:


The code checks the href attribute of each link on the page for 'http', which usually means that the link is to another site (since internal links are normally relative). It then adds a 'target' attribute to the link with a value of '_blank', which opens the page in a new tab. This saves having to ensure that each external link has the target attribute set properly.

The 'target' attribute was deprecated in an HTML4 spec, but is being reintroduced in HTML5.


As pointed out by Sepith, using Javascript's window.location.hostname will avoid adding target="_blank" to internal links containing 'http':

$('a').each(function() {
    var link = $(this);
    if(link.attr('href').indexOf(window.location.hostname) === -1) {
        link.attr('target', '_blank');