Open External Links in a New Window

A common practice with web links is to make sure that links to other websites open in a new tab. At the same time, all links to other pages on the same site should open in the current browser tab. It is important to understand why this approach is a best practice. For starters, visitors to your site would get super-annoyed if every link on your site opened up a new browser tab; so it is important to keep the user on the current browser tab as much as possible and as long as it makes sense. However, as a site owner, you want to make sure that visitors stay on your site as long as possible and don’t navigate away. Since it isn’t reasonable to expect that visitors would never click on a link that takes them away from the site, the best thing to do would be to keep your site open in the current tab and open any external sites in a new browser tab.

If you want a link to open in a new browser tab, you would normally just set the target attribute on the link to _blank, like this:

<a href="https://www.google.com/" target="_blank">Click here</a>

The issue with this is that the person creating the link may not know HTML. Even if they are using a content management system that allows them to easily set whether a link opens in a new window or not, it is likely they may not remember to set this every time.

Thankfully, this jQuery snippet can be added to your site and allows you to easily and consistently open external links in a new browser tab:

Comments

  1. This works great except for when using infinite scroll. How would you go about having this function called on loadmore events?

    I am using wpastra theme and its inbuilt infinite scroll.

    Thank you!

  2. I kept at it and found a solution:

    jQuery(document).ready(function($) {
    $(‘a’)
    .filter(‘[href^=”http”], [href^=”//”]’)
    .not(‘[href*=”‘ + window.location.host + ‘”]’)
    .attr(‘rel’, ‘noopener noreferrer’)
    .attr(‘target’, ‘_blank’);
    });

    jQuery(function($)
    {
    $(document).ajaxStop(function()
    {
    $(‘a’)
    .filter(‘[href^=”http”], [href^=”//”]’)
    .not(‘[href*=”‘ + window.location.host + ‘”]’)
    .attr(‘rel’, ‘noopener noreferrer’)
    .attr(‘target’, ‘_blank’); });
    });

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.