Skip to content

Instantly share code, notes, and snippets.

@smdooley
Created May 16, 2022 09:03
Show Gist options
  • Save smdooley/5300caa0bf91cbcd758bbecac555b686 to your computer and use it in GitHub Desktop.
Save smdooley/5300caa0bf91cbcd758bbecac555b686 to your computer and use it in GitHub Desktop.
Google Analytics events for all a tags
jQuery(document).ready(function ($) {
var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined) {
baseHref = jQuery('base').attr('href');
$('a').each(function() {
var href = $(this).attr('href');
if (href && (href.match(/^https?\:/i)) && (!href.match(document.domain))) {
$(this).click(function() {
var extLink = href.replace(/^https?\:\/\//i, '');
ga('send', 'event', 'External', 'Click', extLink);
if ($(this).attr('target') != undefined && $(this).attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = href; }, 200);
return false;
}
});
}
else if (href && href.match(/^mailto\:/i)) {
$(this).click(function() {
var mailLink = href.replace(/^mailto\:/i, '');
ga('send', 'event', 'Email', 'Click', mailLink);
});
}
else if (href && href.match(filetypes)) {
$(this).click(function() {
var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : '';
var filePath = href;
if(extension != '') {
ga('send', 'event', 'Download', '' + extension + '', '' + filePath + '');
}
if ($(this).attr('target') != undefined && $(this).attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = href; }, 200);
return false;
}
});
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment