This tutorial help to open a link in new tab using javascript. The open()
method of window interface is used to open content in the new tab, window or even iframe
.
How to Create Anchor Link
The href attribute of the anchor (a
) element must be set to the URL you want to link to in order to create a link on a web page.
Check out <a href="http://js-tutorials.com/">js-tutorials.com</a>
Output: Check out js-tutorials.com.
If you click on the above link, the browser will open the link in the current window or tab.
Checkout Other tutorials:
- Automatically Detect External URLs and Make Link In JS
- Convert srt to text with regex in JavaScript
- Iterating over a JavaScript Object
- Reading csv file using JavaScript and HTML5
To open a link in a new tab, You need to set target
attribute to _blank.
Check out <a href="http://js-tutorials.com/">js-tutorials.com</a>
Output: Check out js-tutorials.com.
if you click on the above link, the browser will open up in a new tab, or a new window depending on the person’s browser settings.
window.open method
The window.open()
method allows you to open a new browser window without leaving the current page.
Syntax:
window.open(URL, Target, WindowFeatures);
- URL: This is the link of the webpage that has to be linked.
-
Target: The can be
_blank
,_self
,_parent
,_top
. This means where to load the URL. Like _self will open the link in the same tab which you are working on,_blank
will open the link in the new tab. - WindowFeatures: This specified for the new window that opens like the width, height, screenX, screenY, popup, etc.
The basic method takes two arguments: the URL you want to open and a string that specifies the target window where the URL should be opened.
Here’s an basic example:
const openInNewTab = (url) => { window.open(url, "_blank"); }
Let’s call the function directly:
openInNewTab("http://js-tutorials.com.com/");
Using the Button onclick Event
You can also create specific functions for individual URLs, and
Let’s create a sample example that will open a link in new tab, We’ll append the onclick
Event to your HTML button.
<!DOCTYPE html> <html> <head> <title>How To Open JavaScript Link in New Tab</title> </head> <body> <button onclick="window.open('http://js-tutorials.com','_blank');"> CLICK HERE </button> </body> </html>