Last active
November 7, 2023 22:40
-
-
Save allybee/5871749 to your computer and use it in GitHub Desktop.
Add target="_blank" to external links with pure JavaScript.
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
function targetBlank() { | |
// remove subdomain of current site's url and setup regex | |
var internal = location.host.replace("www.", ""); | |
internal = new RegExp(internal, "i"); | |
var a = document.getElementsByTagName('a'); // then, grab every link on the page | |
for (var i = 0; i < a.length; i++) { | |
var href = a[i].host; // set the host of each link | |
if( !internal.test(href) ) { // make sure the href doesn't contain current site's host | |
a[i].setAttribute('target', '_blank'); // if it doesn't, set attributes | |
} | |
} | |
}; |
To add this code to your WordPress website, you can download a plugin to add JavaScript code. One of such plugins is the Simple Custom CSS and JS plugin by SilkyPress.com.
This plugin is awesome as it allows you to add script tags to either the header or footer. It also gives the option of linking the file either as an internal or external file. Last but not the least, it allows you to set the location in which the script tags affect.
I hope this is able to help anyone who finds this.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!