Last active
December 16, 2015 20:29
-
-
Save nzjames/5493279 to your computer and use it in GitHub Desktop.
Google Analytics tracking helper
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 | |
* | |
* 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); |
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
... | |
<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