Skip to content

Instantly share code, notes, and snippets.

@trangsihung
Forked from CrocoDillon/_blank.js
Created March 2, 2020 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trangsihung/8f5543e787644bd1c1c77512d67d9761 to your computer and use it in GitHub Desktop.
Save trangsihung/8f5543e787644bd1c1c77512d67d9761 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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment