Skip to content

Instantly share code, notes, and snippets.

@CrocoDillon
Last active August 30, 2023 21:27
Show Gist options
  • Save CrocoDillon/7989214 to your computer and use it in GitHub Desktop.
Save CrocoDillon/7989214 to your computer and use it in GitHub Desktop.
Automatically open external links in new tab or window.
// vanilla JavaScript
var links = document.links;
for (var i = 0, linksLength = links.length; i < linksLength; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
// or in jQuery
$(document.links).filter(function() {
return this.hostname != window.location.hostname;
}).attr('target', '_blank');
@alancwoo
Copy link

Quick ES6 version:

let links = [...document.links].forEach((link) => {
  if (link.hostname != window.location.hostname) {
    link.target = '_blank'
  }
})

@OliverBalfour
Copy link

Or just:

[...document.links].forEach(link => {
  if (link.hostname != window.location.hostname)
    link.target = '_blank'
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment