Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open external links in a new tab without jQuery

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;
    }
});
like image 426
AlecRust Avatar asked Oct 20 '12 11:10

AlecRust


People also ask

Can you make the link open in a new tab JavaScript?

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.

How do I make a link open in a new tab in WordPress?

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.”

Why does a new tab open external links?

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.


1 Answers

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();
like image 196
eyecatchUp Avatar answered Oct 29 '22 14:10

eyecatchUp