Created
January 12, 2015 04:57
-
-
Save dalethedeveloper/8bbc30e847543fac088b to your computer and use it in GitHub Desktop.
Plain Javascript to normalize target attribute for External Links
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
<script> | |
// I needed to trigger a non-interactive Google Analytics Event on external link click in | |
// Google Tag Manager v2. This is a hacky workaround for targeting external links on using | |
// a trigger like this: | |
// Event Type: Link Click [element: target] [starts with] ["_"] | |
// This is used as a HTML tag in Google Tag Manager v2 to normalize all external <A> links | |
// to have a "target" attribute. Priority 100, Triggered on All Pages and Event = gtm.dom | |
(function(){ | |
// Find external links and fix target (target not set, href isn't relative, current domain isn't in href) | |
var fixlinks = document.querySelectorAll('a:not([target]):not([href*="'+window.location.host+'"]):not([href^="/"])'); | |
for (var i=0; i<fixlinks.length; i++){ | |
fixlinks[i].setAttribute('target', '_blank'); // or, more semantically rel=external | |
} | |
}()); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment