Skip to content

Instantly share code, notes, and snippets.

@dalethedeveloper
Created January 12, 2015 04:57
Show Gist options
  • Save dalethedeveloper/8bbc30e847543fac088b to your computer and use it in GitHub Desktop.
Save dalethedeveloper/8bbc30e847543fac088b to your computer and use it in GitHub Desktop.
Plain Javascript to normalize target attribute for External Links
<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