Open a Link in a new tab on Button click in JavaScript

avatar

Borislav Hadzhiev

Tue Mar 29 20222 min read

Open a Link in a new tab on Button click in JavaScript #

To open a link in a new tab on button click:

  1. Select the button element.
  2. Add an event listener to the button.
  3. Use the window.open() method to open a link in a new tab.
  4. For example, window.open('https://example.com', '_blank')

Here are the contents of our index.html file.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <button onclick="window.open('https://google.com', '_blank')"> Open Google in new tab </button> <button id="example-btn">Open Example in new tab</button> <script src="index.js"></script> </body> </html>
The first button in the file has an inline click handler and the second button only has an id attribute set.

Here is our index.js file.

index.js
const exampleBtn = document.getElementById('example-btn'); exampleBtn.addEventListener('click', () => { window.open('https://example.com', '_blank'); });

We used the document.getElementById method to select the button element.

The function we passed to the addEventListener method gets called every time the button is clicked.

In my opinion defining a separate click handler is the much cleaner approach.

The first button in the index.html file uses an inline click handler, however, it's much harder to get IDE support with inline event handlers than it is when writing code in a file with a .js extension.

The window.open method loads the specified url into a new or existing browsing context.

The first parameter we passed to the method is the url string.

Make sure that you prefix the URL with the protocol, e.g. https:// if you are linking to an external resource.

The second parameter the window.open() method takes is the target - a string that specifies the name of the browsing context.

By setting target to _blank, we open the resource in a new tab.

Technically, users are able to configure their browser to open the resource in a new window (not tab) when target is set to _blank, but this is very rare.

Another target option that's commonly used is _self - which opens the URL in the current browsing context.

You can view all possibly target options in this section of the MDN docs.

You might have also seen target being set to _blank with anchor <a> elements.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <button onclick="window.open('https://google.com', '_blank')"> Open Google in new tab </button> <button id="example-btn">Open Example in new tab</button> <!-- 👇️ can also set target _blank on anchor elements --> <a href="https://google.com" target="_blank">Google</a> <script src="index.js"></script> </body> </html>
Use the search field on my Home Page to filter through my more than 1,000 articles.