Skip to content

Instantly share code, notes, and snippets.

@subhaze
Last active April 4, 2023 20:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save subhaze/8355725 to your computer and use it in GitHub Desktop.
Save subhaze/8355725 to your computer and use it in GitHub Desktop.
quick and dirty GA event tag dispatcher for jQuery
// GA event tracking
// example usage: (a button is used but any HTML element can be used.)
//
// <button data-ga-track-event='["category", "action", "opt_label", "opt_value", "opt_noninteraction"]'>some action</button>
//
// NOTICE: the usage of '' to wrap the attribute value and the "" used for strings
// This is important since it MUST be valid JSON
$(document.body).on('click', '[data-ga-track-event]', function(e){
var trackData = $(this).data('ga-track-event');
if(!$.isArray(trackData)) throw new Error('[data-ga-track-event] must be a valid JSON array');
if(window._gaq){
trackData.unshift('_trackEvent');
window._gaq.push(trackData);
}else if(window.ga){
trackData.unshift('event');
trackData.unshift('send');
ga.apply(null, trackdata);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment