Jens Segers on

jQuery: open external links in a new window

While working on some websites I needed a javascript that would open all external links in a new windows. So I did a quick search on google, only to find a lot of different solutions for this problem. Most of them used a (too) simple solution like this:

$(document).ready(function(){
    $("a[href^='http']").attr('target','_blank');
});

This code will open all links that start with "http" in a new window. This usually does the trick but lately I tend to use full url links on my website. So that the internal links also begin with http. No problem, there's nothing jQuery can't do! Look at this code:

$(document).ready(function(){
    $("a[href^='http']").not("[href*='"+location.hostname+"']").attr('target','_blank');
});

I added the jQuery not-selector and the problem is fixed. This not-selector filters out all links with a href that contain the current hostname, which is the website's subdomain + domain. Even I did not thought of the jQuery not-selector at first.

If you have any thoughts about improving the "performance", please contact me.

http://api.jquery.com/category/selectors

Webmentions

Tweet about this blog post and you will appear below!