Last active
August 30, 2023 21:27
-
-
Save CrocoDillon/7989214 to your computer and use it in GitHub Desktop.
Automatically open external links in new tab or window.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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'); |
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
Quick ES6 version: