Opening a link in a new tab has to be a calculated decision as it partially breaks the flow thus impacting user experience. But, it is also important to use this when the information on the new page is either short-lived or something that the user want to see, but at the same time continue scrolling the current page.
This method can be used in any JavaScript project or any JavaScript oriented libraries (React) or frameworks (Angular).
Using <a>
tag
Using target
attribute of the anchor tag can be used to open the link in new tab.
<a href="http://noteshub.co.in/" target="_blank">Open Link in New Tab</a>
The "target" attribute specifies where to open the link. Possible values for the attribute are:
-
_blank
: Opens in new tab -
_self
: Opens in the current tab (default)
There are other possible values for "target" attribute. Please see here or here.
THROUGH A FUNCTION
We will be using the window
object of JavaScript.
/**
* Opens the link in new tab
* @param {string} link - Link to open in new tab
*/
openInANewTab(link) {
window.open(link, "_blank");
}
The catch here is that if the user has blocked pop-ups in his/her browser, then this might not work. The browser does show a warning. If the user allows to show pop-up windows for your domain, it will start working again.
Originally published on adityatyagi.com
Top comments (0)