Skip to content

Instantly share code, notes, and snippets.

@NickDeckerDevs
Last active October 18, 2018 13:52
Show Gist options
  • Save NickDeckerDevs/0cbdb766b58353f1cf319a89eb0bc15c to your computer and use it in GitHub Desktop.
Save NickDeckerDevs/0cbdb766b58353f1cf319a89eb0bc15c to your computer and use it in GitHub Desktop.
Outbound link tracking - google analytics jquery / javascript
jQuery(document).ready(function($) {
var trackOutboundLink = function(url, category) {
// debugger;
ga('send', 'event', category, 'click', url, {
'transport': 'beacon',
'hitCallback': function() {
document.location = url;
}
});
}
function addClickOnOutboundLink(link, category) {
var href = link.attr('href');
link.on('click', function(e) {
e.preventDefault();
// debugger;
trackOutboundLink(href, category);
});
}
var clientDomain = document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0];
$('a').each(function() {
var linkElement = $(this);
var href = linkElement.attr('href');
if(href != null) {
if(href.indexOf('mailto:') > -1) {
addClickOnOutboundLink(linkElement, 'Email');
}
if((href.indexOf('http://') > -1 || href.indexOf('https://') > -1) && href.indexOf(clientDomain) == -1) {
addClickOnOutboundLink(linkElement, 'Outbound');
}
if(href.indexOf('tel:') > -1) {
addClickOnOutboundLink(linkElement, 'Phone Call');
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment