Javascript that makes all external links open in a new tab

J

Although best practice is to define where a hyperlink opens per link, you can use javascript to determine how external links work per page or even sitewide.

For instance, on my Tumblr-based portfolio site, I do not have specific control in my navigation to decide if links open in the same tab or a new tab. So, I added a javascript function to force all external links on my site to open in a new tab.

Code

<script>
document.addEventListener('DOMContentLoaded', () => {
  const links = document.querySelectorAll('a');

  links.forEach(link => {
    const isExternal = !link.href.startsWith(window.location.origin);

    if (isExternal) {
      link.setAttribute('target', '_blank');
      link.setAttribute('rel', 'noopener noreferrer');
    }
  });
});
</script>

What to know about this script

DOMContentLoaded Event: The script runs once the DOM is fully loaded, which means it doesn’t block the rendering of the page.

Query Selector: It uses document.querySelectorAll('a'), which is efficient for selecting anchor tags.

Simple Logic: The logic inside the loop is straightforward—checking if a link is external and then setting attributes. This is a lightweight operation.

How this Javascript’s function works

Here’s a breakdown of how it works:

  1. Event Listener: The document.addEventListener('DOMContentLoaded', () => {...}); line sets up a function to be called when the DOM is ready.
  2. Selecting Links: const links = document.querySelectorAll('a'); selects all anchor (<a>) elements in the document.
  3. Looping Through Links: The links.forEach(link => {...}); loop goes through each link.
  4. Checking External Links: It checks if each link’s href does not start with the current site’s origin, identifying it as an external link.
  5. Setting Attributes: If a link is external, it sets the target attribute to _blank and the rel attribute to noopener noreferrer for security and performance reasons.

Happy Coding!

About the author

Kelly Barkhurst

Designer to Fullstack is my place to geek out and share tech solutions from my day-to-day as a graphic designer, programmer, and business owner (portfolio). I also write on Arts and Bricks, a parenting blog and decal shop that embraces my family’s love of Art and LEGO bricks!

Add comment

By Kelly Barkhurst

Recent Posts

Archives

Categories