Created
May 16, 2022 09:03
-
-
Save smdooley/5300caa0bf91cbcd758bbecac555b686 to your computer and use it in GitHub Desktop.
Google Analytics events for all a tags
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
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; | |
} | |
}); | |
} | |
}); | |
} | |
}); |
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
TBC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment