Skip to content

Instantly share code, notes, and snippets.

@tedw
Created May 30, 2013 21:41
Show Gist options
  • Save tedw/5681488 to your computer and use it in GitHub Desktop.
Save tedw/5681488 to your computer and use it in GitHub Desktop.
Google Analytics event tracking using 'data-track-event' attribute on links
/* Google Analytics event tracking using data attribute */
var analyticsTrackEvent = function() {
$('[data-track-event]').on('click', function () {
var trackEventData = $(this).data('track-event') || '';
if ( trackEventData.length ) {
var eventArray = trackEventData.split(',');
// Make sure there are at least 2 values
if ( eventArray.length >= 2 ) {
// Split up the track event data into GA variables
var trackCategory = eventArray[0], // Required (String)
trackAction = eventArray[1], // Required (String)
trackLabel = eventArray[2], // Optional (String)
trackValue = eventArray[3]; // Optional (Number)
// Send event data to GA
ga('send', 'event', trackCategory, trackAction, trackLabel, trackValue);
console.log(trackCategory, trackAction, trackLabel, trackValue);
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment