Shoora
10/18/2018 - 12:14 PM

jQuery Google Analytics Event Tracking Using HTML Attributes

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")
  }
});