Open a link in a new tab on button click in JavaScript

Open a link in a new tab on button click in JavaScript

Posted by Ervin Adams on July 24, 2022

Open a link in a new tab on button click in JavaScript

Open a link in a new tab on button click in JavaScript

Posted by Ervin Adams on July 24, 2022

Here are the steps to take in order to open a link in a new tab on button click:

Step 1. Add an event listener to the button

Step 2. Add the window.open method to the event listener

Here are a couple of techniques: 

HTML onclick attribute:

<button type="button" onclick="window.open('https://google.com', '_blank')">Click here</button>

The onclick attribute fires on click of the button element.

JavaScript addEventListener:

HTML

<button type="button" id="open-link">Click here</button>

JS

let openLink = document.getElementById('open-link');

openLink.addEventListener('click', () => {
  window.open('https://google.com', '_blank');
});

Select the button element using document.getElementById. Once the button is clicked addEventListener will be called.

Any question?
This field is required
Your question have been successfully submitted and will be reviewed before published
Please login to ask a question