external links target blank

Open external links in a new window

Lots of windowsOne of the major goals of a website is to keep uses at your website for as long as possible. One of the easiest things a user can do is leave your website. Therefore at all times we need to encourage users to stay at our websites and we do that in a number of ways.

One way is to make sure all external links open up in a new window. The last thing you want is to provide a link to another website and have that user click on the link to never return to your own website. Here is my jquery code that does this:

$('a').each(function() { if ($(this).attr('href')) { var start = $(this).attr('href').indexOf('://'); if (start != -1) { var parts = $(this).attr('href').split('://'); var end = parts[1].indexOf('/') != -1 ? parts[1].indexOf('/') : parts[1].length; if (parts[1].substr(0, end) != document.domain) { $(this).attr('target', '_blank'); } } } });

The benefits of the above code is that you don't need to use the target attribute which is deprecated. It also allows clients to add in new content and links and have the external links open in a new window. The above code or a similiar piece of code should become part of your own javascript library.