Created
September 6, 2012 08:43
-
-
Save rviscomi/3653191 to your computer and use it in GitHub Desktop.
Automatically trigger Google Analytics events by setting data attributes on HTML elements to track.
This file contains hidden or 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
/* Custom event-tracker wrapper function. */ | |
function trackEvent(category, action) { | |
if (!category || !action) { | |
console.warn('trackEvent takes a category and an action.'); | |
} | |
else { | |
_gaq.push(['_trackEvent'].concat([].slice.call(arguments))); | |
} | |
} | |
/* Support data attributes for events. */ | |
/* data-event="event_name(s)|category|action|label|value|noninteraction" */ | |
$(document).ready(function () { | |
$('[data-event]').each(function () { | |
var data = $(this).data('event').split('|'); | |
$(this).on(data.shift(), function () { | |
trackEvent.apply(null, data); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example use:
Events will be triggered when the button is clicked and when the div is hovered over/out.
The format of the data attribute value must be: event_name(s)|category|action|label|value|noninteraction
The only required tokens are: event_name(s), category, and action.