In HTML we use an anchor tag <a> for a hyperlink to another page. For Open URL in New Tab Using JavaScript, we use the anchor tag target attribute to open in a new tab using JavaScript.
In HTML anchor <a> tag’s target attribute provides a simple way to open a new tab or new window of the browser. We use _blank as a value in the target attribute in the anchor tag. Check below,
1 |
<a href="http://www.codingtasks.net" target="_blank">Visit PHPCODER.TECH</a> |
If you want to do the with javascript to open a link in a new tab, then we can use the window.open() the method as the best option in javascript.
window.open() method take two parameters,
- URL
- _blank value
To know more about window.open() method check here: https://developer.mozilla.org/en-US/docs/Web/API/Window/open
Syntax:
1 |
window.open("URL", "_blank"); |
Example of Open URL in New Tab By Using JavaScript
Below example shows provide URL open in new tab using JS.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<html> <body> <p>Click the button to open a new tab </p> <button onclick="NewTabJS()"> Open PHPCODER.TECH </button> <script> function NewTabJS() { window.open("http://www.codingtasks.net", "_blank"); } </script> </body> </html> |
Code Highlights:
- In the above example, we create an HTML button where we call a JS function on onclick event to open in a new tab using JS code.
- Now we create a JS script, where we use the window open method to open URL in a new tab by JavaScript.
- Window open method takes two parameters,
- URL: which opens in new tab JS.
- To open in a new tab we mainly use _blank attribute as the second parameter.
Here is the complete source code and explanation of open URL in new tab using JS.
Also Check:
Tags: #javascript #window.open() #JavaScriptwindow.openNewTtab
Happy Coding..!
13 Replies to “Open URL in New Tab Using JavaScript”