JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to open a link in a new tab on a button click in JavaScript?

There are two ways using which you can open a link in a new tab on a button click:

  1. Using inline click handler
  2. Using an event listener

How to open a link in a new tab using an inline click handler?

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <button onclick="window.open('https://www.google.com', '_blank')">Click Here</button>
</body>
</html>

window.open() method is used to open a link in a new tab. You pass two parameters to the window.open() method:

  • The first parameter is the URL that you want to open.
  • The second parameter is the target string. In simple terms, how do you want to open the URL? If you mention _blank, then URL opens in a new tab. On the other hand, if you specify _self, then URL opens in the current tab.

It is important to note that the onclick attribute is called when someone clicks on the button.

How to open a link in a new tab using an event listener?

index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <button id="btn">Click Here</button>
</body>
</html>
index.js
let button = document.getElementById('btn');
button.addEventListener('click', ()=>{
  window.open('https://www.google.com', '_blank');
});

Explanation of the code:

1. document.getElementById() method is used to select an HTML element. It accepts an id assigned to the HTML element. In this example, the button element is assigned an id value of btn.

2. After selecting the button, the addEventListener() method is called to register a click event on the button. Then, inside the callback function, window.open() method is invoked.

3. The callback function registered with the click event will be called whenever a button is clicked.