Open External Links in a New Tab Using JavaScript

Published:

|

Updated:

By default, web browsers open all links (whether external or internal) in the same browser tab. Unfortunately, this has a few drawbacks in terms of SEO.

In this beginners' tutorial, we'll see the cons of opening external URLs in the same tab and how to prevent that by writing pure and simple JavaScript.

Along the way, I'll also mention why you should no longer use jQuery or any other library to achieve this.

Let's get started.

Open External Links in a New Tab Using JavaScript

Should External Links Open in a New Tab?

First, let's discuss if external links should open in a new tab.

Generally, all external links should be opened in a new browser tab.

There are many benefits and reasons behind this, but we'll look at two important reasons below.

Reason 1 - Bounce Rate and SEO Impacts

Let's assume you have a link to Google Search somewhere on your web page.

Visitors who click on that link will be redirected to Google Search.

As a result, this will negatively impact your site's SEO by increasing the bounce rate.

Reason 2 - User Experience

A good user experience (UX) ensures all internal links open in the same browsing tab and all external links in a new tab.

This is also intuitive in terms of UX because users wouldn't expect to suddenly leave your site if they read an article and click on an outbound link.

DO NOT Use jQuery

In this section, I'll mention why you should NO longer use jQuery to open URLs in a new tab.

Reason 1 - jQuery Library will Slow Your Site Down

If you only want to use it to open links in new tabs, you're degrading your website performance by adding unnecessary script overhead.

jQuery contains lots of code. As of writing this tutorial, the current jQuery version 3.6.1 is about 88 KB in compressed form. That's a LOT for this simple task.

Unless you're using jQuery extensively for other functionalities on your site, you should avoid using it for opening links in new tabs.

Therefore, you should use pure or vanilla JavaScript to achieve simple tasks like this to avoid high JS payload as possible.

Reason 2 - JavaScript Has New APIs and Features

In the past, it was reasonable for people to use a library like jQuery, Vue, or React to achieve that because of the lack of browser APIs and other features.

But with the modern JavaScript versions, we can accomplish simple tasks like opening links in new browser windows or tabs without using any JavaScript framework or library.

Getting Started

Now, let's see how to use JS to do the following.

  • Detect if a link on our site is external.
  • If it's an external link, add the target attribute with the _blank value to it so that it opens up in a new tab or window.
  • Ensure the internal links are not opened in a new window or tab.

There are two common ways to achieve this.

  • An automated method using pure JavaScript code.
  • Manually adding the target attribute to our HTML files wherever the links appear.

The target HTML Attribute

The target HTML attribute allows you to set how you want your site links to open in the browsing context when a user clicks on them.

For instance, you can configure your anchor links to open in a browser window, a new tab, or on the same browsing tab.

Read more about it on this MDN page.

Open External Links Automatically with JavaScript Code

Step 1 - Writing the JavaScript Code

Launch your preferred source code editor like VS Code.

Create a new file and copy/paste the following code into it.

let anchorLinks = document.querySelectorAll("a");

for (let i = 0; i < anchorLinks.length; i += 1) {
  if (anchorLinks[i].host !== window.location.hostname) {
    anchorLinks[i].setAttribute("target", "_blank");
  }
}

Save the file as index.js.

Understanding the Script

Line 1 grabs the reference to all the anchor links on the page using document.querySelectorAll and stores them in a variable called anchorLinks.

Line 3-7 is the for loop. It's used to go through all the anchor links on the page.

Inside this for loop, on line 4, we apply a condition to check if the anchor link URL does not match that of our website URL.

On line 5, if the condition is true, we use setAttribute to add the target attribute with the _blank value to all the links.

Step 2 - Creating a Simple HTML Web Page

Next, create a simple HTML web page (index.html, in the same directory as index.js) with a few internal and external links, like the following.

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<title>Open External Links in a New Tab Using JavaScript</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<script defer src="./index.js"></script>
</head>

<body>

	<main>
		<a href="https://www.google.com/">Google (external link)</a><br>
		<a href="https://developer.mozilla.org/en-US/">MDN (external link)</a><br>
		<a href="./about.html">About page (internal link)</a>
	</main>

</body>
</html>

Now, open the web page and click on any external link.

Notice how the link opens in a new tab instead of the same tab.

On the other hand, the internal link should use the same browsing tab.

Adding the target Attribute to the HTML Code Manually

The above automated method is ideal if there are many external links (say, 100 or more).

However, if your website has a few links (say, 5-10), it'd be best to manually add the _target attribute to your anchor links.

This would benefit your site because there'd be no unnecessary script delay/execution when a visitor comes to your site.

Conclusion

We learned how to open our outbound links in a new tab. Along the way, we also saw the benefits of doing so.

And if you haven't already, consider subscribing to my newsletter for more coding tips and tricks and other web development tutorials.

FAQs About Opening External Links in a New Tab

Should Outbound Links Open in a New Tab?

Generally speaking, yes. External or outbound links should be opened in a new tab.

How Do I Make an External Link Open in a New Tab?

To make an external link open in a new tab, simply add the target="_blank" attribute to the anchor link. For detailed instructions, follow the steps mentioned above in the tutorial.

Should I Use jQuery to Open External Links in a New Tab?

You don't need to use jQuery to open external links in a new tab. Instead, you can achieve this with pure JavaScript using a few lines of code.

Contents

    Danial Zahid's headshot.

    About Danial Zahid

    I'm a self-taught web developer passionate about everything related to websites and web development. Over the past years, I've explored and worked with different web technologies and tools, notably WordPress, Eleventy, npm, and Gulp.js, to name a few.

    In addition, I've created and currently maintain several open-source projects, including web apps, widgets, websites, and more.

    When I'm not writing content for W3Things or doing web development work, I enjoy my free time by playing games or listening to podcasts.

    Get Essential Gulp Kit

    The ultimate Gulp.js solution to improve your developer experience.

    • Includes complete Gulp.js toolkit setup
    • Optimize website content and static assets
    • Continuous asset optimization during development phase
    • Optimize unlimited number of files in bulk
    • Plus many more awesome features

    Subscribe to the Newsletter

    This website uses cookies to optimize your site experience. By continuing to use the site, you are agreeing to its privacy policy and the use of cookies.