Skip to content

Instantly share code, notes, and snippets.

@rolandinsh
Forked from cheynewallace/ga-event-tracker.js
Created February 2, 2017 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolandinsh/f1dcb020893ca2ab8219df821bd569c7 to your computer and use it in GitHub Desktop.
Save rolandinsh/f1dcb020893ca2ab8219df821bd569c7 to your computer and use it in GitHub Desktop.
jQuery Google Analytics Event Tracking Using HTML Attributes
/*JSHint Options*/
/*global _gaq */
/*
Google Analytics Event Tracking - JSHint Checked
Written By Cheyne Wallace - 19th Nov 2012
Click Usage: <a href="http://somewhere"
class="ga-track"
event_category="Event Category"
event_action="Specific Action"
event_label="Optional Message"
event_value="Optional Value">
Download</a>
*/
jQuery(document).ready(function(){
if (typeof(_gaq) !== "undefined") {
jQuery(".ga-track").click(function(e){
var url;
var isA = $(this).is("a");
// Check For Anchor Tag
if(isA) {
e.preventDefault();
url = this.href;
}
// Setup The Options
var options = {
category: $(this).attr("event_category") || '',
action: $(this).attr("event_action") || '',
label: $(this).attr("event_label") || '',
value: $(this).attr("event_value") || 0
};
// Push To Google
_gaq.push(['_trackEvent', options.category, options.action, options.label, options.value]);
// Give _gaq Time To Push
if (isA){setTimeout(function(){location.href = url;}, 110);}
});
}
else {
// Analytics not activated - Most likely devevelopment env - Do nothing
//console.log("Missing Analytics Analytics Tracking Code")
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment