Borislav Hadzhiev
Tue Mar 29 2022·2 min read
Photo by Tessa Rampersad
To open a link in a new tab on button click:
window.open()
method to open a link in a new tab.window.open('https://example.com', '_blank')
Here are the contents of our index.html
file.
<!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>
id
attribute set.Here is our index.js
file.
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.
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.
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.
<!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>