How to Open URL in New Tab in JavaScript

How to Open URL in New Tab in JavaScript

Typically, when we click a link on a web page it is opened in the same tab of web browser and user is taken to the new URL. Often we need to open URL in new tab of the same browser, not a new window. This functionality can be implemented on your web pages using JavaScript. In this article, we will learn how to open URL in new tab in JavaScript.

How to Open URL in New Tab in JavaScript

Here is the HTML code for a link.

<a id='myLink' href='/path/to/url'>Click me</a>

Typically, if you want to open URL in new tab, you just need to add target=”_blank” in your URL as shown below.

<a id='myLink' href='/path/to/url' target='_blank'>Click me</a>

But sometimes you may want to add this function dynamically. In such cases, define a JavaScript function as shown below.

function openInNewTab(url) {
  window.open(url, '_blank').focus();
}

// Or
window.open(url, '_blank').focus();

The above code will open all URLs on your web page in new tabs. If that does not happen, then you can explicitly add a call handler to your URL, to enable it.

<a id='myLink' onclick="openInNewTab('www.test.com');">Click me</a>

Please note, this can be applied to other HTML elements such as Divs as well.

<div onclick="openInNewTab('www.test.com');">Click me</div>

By adding the click handler to specific links you can selectively open only certain links in new tab instead of opening them all.

If you use a third-party library like jQuery that allow you to easily select elements by class, name, id, attribute, etc. then you can use this feature to selectively open links with a specific class, name, id, or attribute to open in new tab. Here is an example to only open all links with class=myClass in new tab and leave other URLs on your web page untouched.

 $(".myClass").on("click",function(){
         window.open('www.test.com','_blank');
     });

In this article, we have learnt how to open URL in new tab in JavaScript. You can use it anywhere on your page to add the functionality as per your requirement.

Also read:

How to Copy Array in JavaScript
How to Merge Two JavaScript Object Properties
How to Check if JavaScript Array Includes Value
What is JavaScript Version of Sleep
How to Fix Floating Point Precision in JavaScript

Leave a Reply

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