Skip to content

Instantly share code, notes, and snippets.

@mrpunkin
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save mrpunkin/b1a251f55dc3176c049e to your computer and use it in GitHub Desktop.

Select an option

Save mrpunkin/b1a251f55dc3176c049e to your computer and use it in GitHub Desktop.
jQuery event handler to track a Google Analytics (analytics.js) event and continue with the element's default HTML action, such as a form submit, link follow, etc.
// Event Handler
var trackEventAndContinue;
(function($, undef){
trackEventAndContinue = function(e){
e.preventDefault();
if((this.disabled !== undef && this.disabled) || $(this).hasClass('disabled')) return false;
$(this).unbind(e);
var opts = {
'hitType': 'event',
'eventCategory': e.data.category,
'eventAction': e.data.action,
'eventLabel': e.data.label,
'eventValue': e.data.value,
'hitCallback': function(){
$(e.target).trigger(e.type);
}
};
ga('send', opts);
};
})(jQuery);
// Use Case
$('a.mylink').click({
category: 'button',
action: 'click',
label: 'Awesome Button'
}, trackEventAndContinue);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment