Skip to content

Instantly share code, notes, and snippets.

@mimetaur
Last active April 4, 2023 20:04
Show Gist options
  • Save mimetaur/6977294 to your computer and use it in GitHub Desktop.
Save mimetaur/6977294 to your computer and use it in GitHub Desktop.
Simple tracker code for GA
$.fn.track = function(event) {
event = typeof event !== 'undefined' ? event : 'click';
if(!window.console){ window.console = {log: function(){} }; }
$(this).on(event, function(e) {
var category = $(this).data('category');
var action = $(this).data('action');
var label = $(this).data('label');
try {
if (category && action && label) {
console.log('ga track event: ', category, action, label);
ga('send', 'event', category, action, label);
} else if (category && action) {
console.log('ga track event: ', category, action);
ga('send', 'event', category, action);
}
}
catch(e) {
console.log(e.name, e.message);
}
})
};
@mimetaur
Copy link
Author

Examples
(click is the default event)

$("#my-button").track()
$("form").track('submit')
$(".rollover").track("mouseover")

@mimetaur
Copy link
Author

Example html:
<a href="#" id="my-button" data-category="myCategory" data-action="myAction" data-label="myLabel"

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