Skip to content

Instantly share code, notes, and snippets.

@yrcjaya
Last active April 6, 2020 16:10
Show Gist options
  • Save yrcjaya/4e5448497a9c0bfab10b to your computer and use it in GitHub Desktop.
Save yrcjaya/4e5448497a9c0bfab10b to your computer and use it in GitHub Desktop.
Google Analytics click event tracker as data attribute. Uses jQuery for event handling
/**
* Google analytics tracking
* add attribute data-ga-event with json encoded dictionary
* with keys eventLabel, eventAction, eventCategory
* eg:
* # Sample JSON structure
* {
* "eventLabel":" Send Event",
* "eventAction": "click",
* "eventCategory": "CTA"
*}
* # Sample HTML tag with data-ga-event attribute
* <p data-ga-event="{&quot;eventLabel&quot;:&quot;Send Event&quot;,&quot;eventAction&quot;:&quot;click&quot;,&quot;eventCategory&quot;:&quot;CTA&quot;}">>Send Event</p>
*/
$(document).on('click.ga', '[data-ga-event]', function(evt) {
var $el = $(this);
var gaData = $el.data('ga-event');
if(gaData) {
$.extend(gaData, {hitType: 'event'});
ga('send', gaData);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment