jQuery - Open external links in a new tab

jQuery - Open external links in a new tab

jQuery - Open external links in a new tab

The target="blank" attribute allows you to force opening of links in new windows. While it is relevant to open external links in a new tab or window, same domain links should definitely be opened in the same window.

This code detect if a link is external, and if yes, adds a target="blank" attribute to it.

$('a').each(function() {
    var a = new RegExp('/' + window.location.host + '/');
    if(!a.test(this.href)) {
        $(this).click(function(event) {
            event.preventDefault();
            event.stopPropagation();
            window.open(this.href, '_blank');
        });
    }
});

Source: [http://css-tricks.com/snippets/jquery/open-external-links-in-new-window/]