How to Open a Link in a New Tab on Button Click in JavaScript
Opening a link in a new tab is a standard web feature. While this is the default behavior of an HTML anchor (<a>) tag, you sometimes need to trigger this action from a <button> element, for example, after a form is processed or as part of a more complex JavaScript interaction. The standard browser method for this is window.open().
This guide will teach you the correct and safe way to use window.open() to open a new tab from a button click, explain the important semantic difference between a <button> and an <a> tag, and cover the critical noopener security feature.
The Core Question: When to Use a Button vs. an Anchor (<a>) Tag
Before implementing, it's important to choose the right HTML element for the job.
- Anchor
<a>Tag: Use this for navigation. Its purpose is to take the user to another page or resource. If your "button" is simply a link styled to look like a button, you should use an<a>tag. It's more accessible and semantically correct.<!-- Best for simple navigation -->
<a href="https://example.com" target="_blank" rel="noopener noreferrer" class="button-style">
Go to Example
</a> <button>Element: Use this for actions. A button triggers a script to perform an action, such as submitting a form, toggling a modal, or, in our case, opening a new tab as part of a larger JavaScript function.
This guide focuses on the case where using a <button> is the correct semantic choice.
The Core Method: window.open()
The window.open() method instructs the browser to load a resource in a new or existing browsing context (i.e., a tab or window).
Syntax:
window.open(url, target, windowFeatures)
For our purpose, we only need the first two arguments:
url: The web address to open. You must include the protocol (e.g.,https://).target: A string specifying where to open the link. To open in a new tab, you must use the special value'_blank'.
window.open('https://example.com', '_blank');
The Solution: Using an Event Listener
The modern and recommended way to handle a button click is with an "unobtrusive" event listener in your JavaScript file. This keeps your HTML clean and separates structure from behavior.
For example, you have a button and want it to open a link when clicked. HTML:
<button id="my-button">Open Example.com</button>
The solution is to attach a click event listener to the button and call window.open() inside the handler.
const myButton = document.getElementById('my-button');
myButton.addEventListener('click', () => {
window.open('https://example.com', '_blank');
});
This is the clean, standard approach. Avoid using inline onclick attributes (<button onclick="...">), as they mix JavaScript into your HTML and are an older practice.