1 min read

Open all external links in a new window

The following line of jQuery will add the relavant target="_blank" attribute to links on the page. It’s best to scope it to a particular class or ID; in this case .content. The code is adapted from one posted on CSS Tricks but makes use of jQuery’s :not() expression. You can also use the same filter selector in your CSS file to style external links differently.

$(document).ready( fucntion(){
$('.content a[href*="//"]:not([href*="mysite.com"]').attr('target','_blank');
});
view raw ready.js hosted with ❤ by GitHub

Adding the attribute to every link when the page loads is not particularly performant. A better solution is to only check whether the link is external or not when it’s clicked; that way the javascript can be deferred until it is actually needed. The use of the jQuery .on() function also means that there need only be one event handler - on the .content element instead of on every anchor.

$('.content').on('click', 'a[href*="//"]:not([href*="mysite.com"])', function(){
$(this).attr('target','_blank');
});
view raw click.js hosted with ❤ by GitHub

This method is used on the page you’re on now. Inspect the code to your heart’s content.

Posted