Skip to content

Instantly share code, notes, and snippets.

@meehow
Last active March 16, 2017 17:02
Show Gist options
  • Save meehow/2655bc5997cc4b14c130a236254b01d5 to your computer and use it in GitHub Desktop.
Save meehow/2655bc5997cc4b14c130a236254b01d5 to your computer and use it in GitHub Desktop.
track outbound links in Google Analytics
var trackOutboundLink = function(event) {
var url = this.href;
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
event.preventDefault();
}
Array.prototype.slice.call(document.getElementsByTagName('a')).map(function(el) {
if (el.href[0] != '/') el.addEventListener('click', trackOutboundLink);
});
@rmehner
Copy link

rmehner commented Mar 16, 2017

For wider Browser support, you may not want to rely on Array.from that is only available in newer browsers ;-) (hi IE11 and Android browser!)

Array.prototype.slice.call(document.getElementsByTagName('a')).map(function(el) {

does the same thing, in all it's ugliness ;)

@meehow
Copy link
Author

meehow commented Mar 16, 2017

Good point. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment