Skip to content

Instantly share code, notes, and snippets.

@rviscomi
Created September 6, 2012 08:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rviscomi/3653191 to your computer and use it in GitHub Desktop.
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.
/* 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);
});
});
});
@rviscomi
Copy link
Author

rviscomi commented Sep 6, 2012

Example use:

<button type="button" data-event="click|GitHub Gist|Click|365319">Whammy</button>
<div id="super-important" data-event="mouseenter mouseleave|GitHub Gist|Hover|365319">...</div>

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.

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