How to Open URL in a New Tab with JavaScript

Open URL in a New Tab with JavaScript

When creating links that open in a new tab, we have to use the "_blank" attribute inside an a (anchor) HTML tag. For example, this is what raw HTML for that would look like:

<a href="https://stackdiary.com/" target="_blank">Click here to open in a new tab</a>

And to do this using JavaScript, you can use the window.open() method.

This method takes two arguments: the URL you want to open and a string that specifies the target window where the URL should be opened.

Here’s an example:

const openInNewTab = (url) => {
  window.open(url, "_blank");
}

You can then call the function directly:

openInNewTab("https://stackdiary.com/");

And this is how you would tie it all together to apply the function to a button, for example:

const openInNewTab = (url) => {
  window.open(url, "_blank");
}

const btn = document.getElementById("open-link-button");

btn.addEventListener("click", () => {
  openInNewTab("https://stackdiary.com/");
});

All you need to do is append the open-link-button class to your button:

<button id="open-link-button">Click me for a demo!</button>

One unique feature of this method is that it also hides the link when a user hovers over it. There are two ways to fix this, the first is to append a HTML title attribute which can also be done with JS.

btn.setAttribute("title", "https://stackdiary.com/");

As an alternative, you could try and implement a tooltip over it – to give your users an idea of what the button does.


Using the onclick Event

You can also create specific functions for individual URLs, and then append the onclick Event to your HTML button.

<button onclick="btnNT()">
Opens in a New Tab
</button>
 
<script>
function btnNT() {
  window.open(
     "https://stackdiary.com/", "_blank");
}
</script>

The onclick event is a JavaScript event that is triggered when an element in a web page is clicked. This event can be attached to any element on a page, and can be used to create interactive elements on a page or to control the behavior of other elements on the page when the element is clicked.

Previous Post
Convert Strings to Arrays in JavaScript

How to Convert Strings to Arrays in JavaScript

Next Post
Common JavaScript Errors

10 Common JavaScript Errors (And How To Fix Them!)

Related Posts