Internet pages comprise exterior hyperlinks that open URLs in a brand new tab. For instance, Wikipedia articles present hyperlinks to open the reference websites in a brand new tab. That is completely for newcomers.
There are 3 ways to open a URL in a brand new tab.
- HTML anchor tags with goal=_blank attribute.
- JavaScript window.open() to set hyperlink and goal.
- JavaScript code to create HTML hyperlink component.
HTML anchor tags with goal=_blank attribute
That is an HTML fundamental that you’re aware of. I added the HTML with the required attributes for the reason that upcoming JavaScript instance works with this base.
<a href="https://www.phppot.com" goal="_blank">Go to Phppot</a>
Eventualities of opening URL by way of JavaScript.
When we have to open a URL on an occasion foundation, it needs to be performed by way of JavaScript at run time. For instance,
- Present the PDF in a brand new tab after clicking generate PDF hyperlink. We have now already seen how one can generate PDFs utilizing JavaScript.
- Present product web page from the gallery by way of Javascript to maintain monitor of the purchasing historical past.
The under two sections have code to learn to obtain opening URLs in a brand new tab utilizing JavaScript.
JavaScript window.open() to set hyperlink and goal
This JavaScript one-line code units the hyperlink to open the window.open methodology. The second parameter is to set the goal to open the linked URL in a brand new tab.
window.open('https://www.phppot.com', '_blank').focus();
The above line makes opening a URL and focuses the newly opened tab.
JavaScript code to create HTML hyperlink component.
This methodology follows the under steps to open a URL in a brand new tab by way of JavaScript.
- Create an anchor tag (<a>) by utilizing the createElement() perform.
- Units the href and the goal properties with the reference of the hyperlink object instantiated in step 1.
- Set off the press occasion of the hyperlink component dynamically created by way of JS.
var url = "https://www.phppot.com";
var hyperlink = doc.createElement("a");
hyperlink.href = url;
hyperlink.goal = "_blank";
hyperlink.click on();
Browsers help: Most trendy browsers help the window.open() JavaScript methodology.