Last updated: Mar 6, 2024
Reading time·3 min
To open a link in a new tab on button click:
window.open()
method to open the 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> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <button onclick="window.open('https://google.com', '_blank')"> Open Google in a 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 a 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
- it opens the URL in
the current browsing context.
You can view all possible target
options in
this section
of the MDN docs.
You might have also seen target
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 a 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>
You can learn more about the related topics by checking out the following tutorials: