There are two ways using which you can open a link in a new tab on a button click:
<!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:
_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.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <button id="btn">Click Here</button> </body> </html>
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.