What's the best way to open all external links (URLs that don't match the current domain) in a new tab using JavaScript, without using jQuery?
Here's the jQuery I'm current using:
// Open external links in new tab
$('a[href^=http]').click(function () {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
window.open(this.href);
return false;
}
});
You need to use the _blank value in the target attribute to open the linked URL in a new tab or window. If you want to open URL with JavaScript, the open() method of Window interface is the best option. The JavaScript window. open() method opens a new browser window.
Manually Set Links to Open in a New Tab (for WordPress) You can easily set external links to open in a new tab in WordPress. In the Classic Editor, just insert your link and click Link Options to open the advanced insert link popup. Then check the box labeled “Open link in a new tab.”
Opening the external links in new tabs allows users to scan the page once, click on all the relevant links and start consuming and sifting information. The user doesn't have to keep going back to the source page to continue scanning for more links to click. There's less interruption in their flow.
Pure JS:
function externalLinks() {
for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
var b = c[a];
b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
}
}
;
externalLinks();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With