Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

How to Open All Links in a New Tab using Javascript

Let's start with a simple example of an a href link in HTML:

<a href="https://www.example.com">Visit Example Website</a>

This creates a basic hyperlink that, when clicked, will navigate to https://www.example.com in the same browser tab or window.

The target="_blank" Attribute

To make a link open in a new tab or window, you can add the target="_blank" attribute to the <a> tag:

<a href="https://www.example.com" target="_blank">
         Visit Example Website
</a>

The target attribute specifies where to open the linked document. When set to "_blank", it tells the browser to open the link in a new tab or window, depending on the user's browser settings.

This approach is useful when you want to keep users on your site while allowing them to explore external content. It is also useful when the link leads to reference materials or supplementary information and you wish to peruse them without disrupting the current page. Essentially this is an approach to provide easy access to external resources without losing context.

However, it's important to use this feature judiciously, as some users prefer to control how links open themselves. Overusing target="_blank" can lead to a cluttered browsing experience and users will not like it.

The rel="noopener noreferrer" attribute

For security reasons, when using target="_blank", it's recommended to also include the rel="noopener noreferrer" attribute:

<a href="https://www.example.com" target="_blank" rel="noopener noreferrer">
Visit Example Website
</a>

This prevents potential exploitation through the window.opener object and enhances security.

Using event listeners to open links in a new tab

How to open links in a new tab

Using event listeners to open links in a new tab

document.addEventListener('DOMContentLoaded', () => {
  const links = document.querySelectorAll('a');
  links.forEach(link => {
    link.setAttribute('target', '_blank');
  });
});

This code snippet adds an event listener that waits for the DOM content to be fully loaded before executing the function. Once the content is loaded, it selects all anchor elements on the page using querySelectorAll('a'). Then, it iterates through each link using the forEach method and sets the target attribute to '_blank', which tells the browser to open the link in a new tab.

In other words this approach works for all links without explicitly updating the anchor tags of each link individually.

If you want to target only external links, you can modify the code slightly to check if the link's href attribute includes 'http' or 'https':

document.addEventListener('DOMContentLoaded', () => {
  const links = document.querySelectorAll('a');
  links.forEach(link => {
    if (link.href.includes('http')) {
      link.setAttribute('target', '_blank');
    }
  });
});

This version of the code will only apply the new tab behavior to links that point to external websites, leaving internal links to open in the same tab. This assumes that individual links are being referred to by their relative path (e.g., “/blog” for the Kodeclik blog as opposed to the absolute path).

Again as mentioned earlier, when implementing this feature, it's also crucial to consider security implications. To prevent potential exploitation through the window.opener object, you should add the rel="noopener noreferrer" attribute to links that open in new tabs. This can be done by modifying the JavaScript code as follows:

document.addEventListener('DOMContentLoaded', () => {
  const links = document.querySelectorAll('a');
  links.forEach(link => {
    if (link.href.includes('http')) {
      link.setAttribute('target', '_blank');
      link.setAttribute('rel', 'noopener noreferrer');
    }
  });
});

This additional security measure helps prevent potential phishing attacks and protects the original page from being manipulated by the newly opened tab.

How to ensure each target opens in a new tab without overlaps

Recall how the basic HTML code looks like for a link that opens in a new tab:

<a href="https://www.example.com" target="_blank">
Example Link
</a>

Tis will open the link in a new tab, but if clicked multiple times, it will reuse the same tab. To ensure that each link target opens in a new tab without overlapping, you can use the target attribute with a unique name for each link.

Here's how you can do it:

<a href="https://www.example1.com" target="tab1">
Example Link 1
</a>
<a href="https://www.example2.com" target="tab2">
Example Link 2
</a>
<a href="https://www.example3.com" target="tab3">
Example Link 3
</a>

By using unique target names (tab1, tab2, tab3), each link will open in its own new tab without overlapping.

If you have many links and don't want to manually assign unique names, you can use JavaScript to dynamically set unique target names.

document.addEventListener('DOMContentLoaded', () => {
  const links = document.querySelectorAll('a[href^="http"]');
  links.forEach((link, index) => {
    link.setAttribute('target', `_blank_${index}`);
    link.setAttribute('rel', 'noopener noreferrer');
  });
});

This script selects all links that start with "http" and sets a unique target name for each (_blank_0, _blank_1, etc.). Again, for security reasons it's recommended to add the rel="noopener noreferrer" attribute to links that open in new tabs. Also again keep in mind that while this approach ensures each link opens in a new tab, it may not be the best user experience for all situations.

If you liked learning how to open links programmatically in Javascript, checkout our blogpost on how to scroll automatically to the bottom of a webpage using Javascript!

Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.