Skip to content

Instantly share code, notes, and snippets.

@MikeMcChillin
Last active June 15, 2016 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeMcChillin/2729e8265d75cbbd7ebad8656fd51514 to your computer and use it in GitHub Desktop.
Save MikeMcChillin/2729e8265d75cbbd7ebad8656fd51514 to your computer and use it in GitHub Desktop.
Google Analytics Click Tracking with jQuery
// Set listeners for click events on elements that have [data-gtm-category] on them
$('[data-gtm-category]').on('click', function() {
var category = $(this).data('gtm-category');
var action = $(this).data('gtm-action');
var label = $(this).data('gtm-label');
gtmClickTrack(category, action, label);
});
// Send the info to Google Analytics
var gtmClickTrack = function(category, action, label) {
ga('send', {
hitType: 'event',
eventCategory: category,
eventAction: action,
eventLabel: label
});
};
// Add data-gtm-* attributes to the element you'd like to track
<a href="#" data-gtm-category="Videos" data-gtm-action="play" data-gtm-label="Fall Campaign">Track this click</a>
<!-- include analytics.js and be sure to change your UA-XXXXX-Y ID -->
<script>
window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;
ga('create','UA-XXXXX-Y','auto');ga('send','pageview')
</script>
<script src="https://www.google-analytics.com/analytics.js" async defer></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment