How to Dynamically Open External Links in New Window

Any web developer will probably know that using the target="_blank" attribute will force any link to open in a new window, which is great for when you want to link to external content or sites but you don't want your user to stray too far from your pages. What's not so great about it, though, is that it can be a real pain to have to remember to add target="_blank" to every single link to external content. It's also a problem if your site has external links that have been added dynamically because they might not even have the target attribute attached to them.

For these reasons, it's often better if you add the target="_blank" attribute dynamically using JavaScript or jQuery. It's actually very easy and straightforward to achieve this, and the code is relatively simple. All you need to do is have the code determine if a link is external or not, and if it is, add the attribute target="_blank". See the code snippet below to learn how to dynamically open external links in new tabs for your projects:

$('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');
      });
   }
});

The snippet above tests whether or not the anchor tag is linking to content within your site by using the window.location.host chained methods and the .test  method. If the anchor tag is found to link to external content, then the target="_blank" attribute will be applied to the anchor tag, and the link will open in a new window or tab. This snippet is super useful if you have a lot of links on your site and find it hard to manage them all, or if you simply are forgetful when it comes to adding that pesky target="_blank" attribute. Either way, it's certainly a simple and useful addition to any project.



Responsive Menu
Add more content here...