Skip to content

Instantly share code, notes, and snippets.

@nzjames
Last active December 16, 2015 20:29
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 nzjames/5493279 to your computer and use it in GitHub Desktop.
Save nzjames/5493279 to your computer and use it in GitHub Desktop.
Google Analytics tracking helper
/**
* Google Analytics tracking
*
* This helper sets up a delegate that responds to on click events for
* all elements that have a data-gcat (GA category)
* attribute and initializes a click or submit track event (submit for input[type=submit])
* and also sends the data-galabel label.
*
* Usage:
* 1. Add to the page footer
<script>
NS.setupAnalyticsTracking();
</script>
*
* 2. Add data-gacat adn data-galabel to links and inputs
* <a href="mailto:tom@example.com" data-gacat="Email" data-galabel="Tom_contact">tom@example.com</a>
*
*/
var namespace = 'NS'
(function (ns){
ns = window[ns] = window[ns] || {};
var setupAnalyticsTracking = function () {
$('body').on('click', '[data-gacat]', function () {
var node = $(this);
var gaMethod = '_trackEvent';
var category = node.data('gacat');
var action = (String(node.attr('type')).toLowerCase() == 'submit') ? 'Submit' : 'Click';
var label = node.data('galabel');
var value = null;
var noninteraction =false;
if (_gaq && _gaq.push && category && action && label) {
_gaq.push([gaMethod, category, action, label, , noninteraction]);
}
});
};
ns.setupAnalyticsTracking = setupAnalyticsTracking;
})(namespace);
...
<a href="mailto:tom@example.com" data-gacat="Email" data-galabel="Tom_contact">tom@example.com</a>
<script>
// If Google analytics has loaded setup tracking
if (_gaq && NS && NS.setupAnalyticsTracking) {
NS.setupAnalyticsTracking();
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment