Web pages contain external links that open URLs in a new tab. For example, Wikipedia articles show links to open the reference sites in a new tab. This is absolutely for beginners.
There are three ways to open a URL in a new tab.
target=_blank
attribute.window.open()
to set hyperlink and target.This is an HTML basic that you are familiar with. I added the HTML with the required attributes since the upcoming JavaScript example works with this base.
<a href="https://www.phppot.com" target="_blank">Go to Phppot</a>
When we need to open a URL on an event basis, it has to be done via JavaScript at run time. For example,
The below two sections have code to learn how to achieve opening URLs in a new tab using JavaScript.
This JavaScript one-line code sets the link to open the window.open
method. The second parameter is to set the target to open the linked URL in a new tab.
window.open('https://www.phppot.com', '_blank').focus();
The above line makes opening a URL and focuses the newly opened tab.
This method follows the below steps to open a URL in a new tab via JavaScript.
<a>
by using the createElement()
function.var url = "https://www.phppot.com";
var link = document.createElement("a");
link.href = url;
link.target = "_blank";
link.click();
Browsers support: Most modern browsers support the window.open()
JavaScript method.