Skip to content

Instantly share code, notes, and snippets.

@Rudis1261
Last active May 11, 2016 21:41
Show Gist options
  • Save Rudis1261/8db90b5d48d6f889890b to your computer and use it in GitHub Desktop.
Save Rudis1261/8db90b5d48d6f889890b to your computer and use it in GitHub Desktop.
GA Universal dataLayer event Tracking
<script type="text/javascript">
/*eslint-env browser*/
/*global ga*/
(function(e) {
'use strict';
function ucfirst(string) {
return string[0].toUpperCase() + string.slice(1);
}
if (Object.keys(e) == 'gaEvent' && typeof ga == 'function') {
var eventDetails = {'hitType': 'event'};
var needles = ['category', 'action', 'label', 'value', 'nonInteraction'];
var maxNeedles = needles.length;
for (var n = 0; n < maxNeedles; n++) {
if (e.gaEvent[needles[n]]) {
var eventName = 'event' + ucfirst(needles[n]);
eventDetails[eventName] = e.gaEvent[needles[n]];
}
}
ga('send', eventDetails);
}
}({{Event}}, ga));
</script>
@Rudis1261
Copy link
Author

Please note this would be triggered by a event like this, I will be abstracting this into the ga-tracking.js script:

<a href="" onClick="dataLayer.push({ 'event' : { 'gaEvent' : { 'category' : 'Testing again', 'action' : 'Testing to see if we will fire multiple events or a single one', 'label' : 'Ga test label, 2.0' } } });" />

@Rudis1261
Copy link
Author

This has been abstracted to a method of it's own, to use it you will need to use it the following way:

gaTrack.send({'category' : 'Newsletters', 'action' : 'Sign-up'});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment