Last active
April 6, 2020 16:10
-
-
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
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
/** | |
* 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="{"eventLabel":"Send Event","eventAction":"click","eventCategory":"CTA"}">>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