How to Open Hyperlink in a New Window
Hyperlinks are used to jump from one page to another. A hyperlink commonly opens in the same page by default. But it is possible to open hyperlinks in a separate window.
Opening external links in a new tab or window will make people leave your website. In this way, you prevent your visitors from returning to your website. Remember that visitors can open a new tab themselves and are irritated when a link opens in a new tab or window without their consent. That’s why it’s recommended to avoid opening links in a new tab or window. However, there can be specific situations when this is needed, and in this snippet, we’ll demonstrate how it can be done.
As you know, in HTML the <a> tag is used with the href attribute for creating hyperlinks.
When it is needed to tell the browser where to open the document, the target attribute is used.
How to Add target="_blank" Attribute to Anchor Link
The target attribute determines where the linked document will open when the link is clicked. It opens the current window by default. To open a link in a new window, you need to add the target="_blank" attribute to your anchor link, like the following.
Example of opening a hyperlink in a new window with the target attribute:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h1>Hyperlink Example</h1>
<p>
This <a href="https://www.w3docs.com/" target="_blank">hyperlink</a> will open in a new tab.
</p>
</body>
</html>
Result
In the given example, when the visitor clicks on the hyperlink, it opens in a new window or tab.
There is another way of opening a hyperlink in a new tab by using the JavaScript window.open function with the onclick event attribute like this:
onclick="window.open('URL')"
Example of opening a hyperlink in a new window with the onclick event:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.link:hover {
text-decoration: underline;
color: blue;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Hyperlink Example with JavaScript</h1>
<p>Visit our website</p>
<a href="https://w3docs.com" onclick="window.open(this.href, '_blank', 'width=500,height=500'); return false;" class="link">W3docs</a>
</body>
</html>
Let’s see one more example, where besides the target attribute, we also add a rel attribute with the “noopener noreferrer” value. The rel attribute is not mandatory, but it’s recommended as a security measure.
Example of opening a link in a new tab with the target and rel attributes:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<a target="_blank" rel="noopener noreferrer" href="https://www.lipsum.com/">Lorem Ipsum</a>
<p>This link will open in a new browser tab or a new window.</p>
</body>
</html>