Shoora
4/22/2019 - 10:01 AM

jquery activity tracking plugin for google analytics events

jquery activity tracking plugin for google analytics events

/**
 * DESCRIPTION:
 * Searches for elements with an 'activity' attribute and pushes the activity
 * to the Google Tag Manager (GTM) dataLayer. GTM must be configured to capture
 * the event data, which is structured as follows:
 *      {
 *          'event': 'eventCategory', // The primary divisions of the types of Events you have on your site.
 *          'eventAction': 'action',    // For example, you could define Play or Pause as Actions for a Video
 *          'eventLabel': 'label', // An optional descriptor that you can use to provide further granularity. You can specify any string for a label.
 *          'eventValue': 10 // An optional numerical variable.
 *      }
 *
 * This is especially useful for recording AJAX type interactions which would
 * not normally register as a Google Analytics page view, but does represent an
 * action by the visitor.
 *
 * USAGE:
 * Add an activity attribute to any HTML element and call the jquery trackActivities plugin on the 
 * appropriate tags. The activity attribute is a comma delimited list of parameters passed to Google's 
 * _trackEvent function, in the following order: category,action,opt_label,opt_value. Note, category and action
 * are required. By default, the activity will be tracked on click, but the event triggers may
 * be overridden using the settings. 
 * Additionally, one can use pushActivity to actively trigger an event. The
 * usage is essentially the same as  trackActivities, except one does not need
 * to pass in events
 *
 * EXAMPLES:
 *      <a href='mysite.com/products/nutsandbolts/' activity='Product,ViewDetailsTab,NutsAndBolts'>Details</a>
 *      <script>$('a').trackActivities();</script>
 *
 *      <select activity='Product,SizeChanged'>
 *          <option value='1'>Small</option>
 *          <option value='2'>Medium</option>
 *          <option value='3'>Large</option>
 *      </select>
 *      <script>
 *      $('select').trackActivities({
 *          'events':['change'], 
 *          'label_callback': function() {
 *              return $(this).find(':selected').text();
 *          },
 *          'value_callback': function() {
 *              return $(this).find(':selected').val();
 *          }
 *      });
 *      </script>
 */
(function($) {
  var defaults = {
      'attribute': 'activity', 
      'delim':',', 
      'events':['click'], 
      'label_callback':null, 
      'value_callback':null
  },

  track_event = function(config) {
    var $this = $(this);

    // dataLayer (Google Tag Manager's dataLayer) is required
    if(typeof dataLayer == 'undefined') return; 

    var activity = $this.attr(config.attribute);

    // If we couldn't find the activity attribute, we can't do anything
    if (typeof activity === "undefined") {
      return;
    }

    var params = activity.split(config.delim);
    if (params.length >= 2) {
        // If we have no label defined in the activity attribute, check for a callback
        if (params.length < 3) {
            var label  = (config.label_callback) ? [config.label_callback.apply(this)] : [];
            params = params.concat(label);
        }
        // Same for value, if not defined, check for it.
        if (params.length == 3) {
            var value = (config.value_callback) ? [config.value_callback.apply(this)] : [];
            params = params.concat(value);
        }

        // Data that will be pushed onto the GTM dataLayer
        var data = {
            'event': params[0], 
            'eventAction': params[1] || '',
            'eventLabel': params[2] || '',
            'eventValue': params[3] || ''
        }
        debug.debug(data);
        dataLayer.push(data);
    }
  },

  bind_event = function(config) {
    var $this = $(this);
    for(var i=0; i<config.events.length; i++)
    {
        $this.bind(config.events[i], function(){
            track_event.apply(this, [config]);
        });
    }
  };

  $.fn.pushActivity = function(settings) {
    settings || (settings = {});
    settings = $.extend({}, defaults, settings);

    track_event.apply(this, [settings]);

    return this;
  }

  $.fn.trackActivities = function(settings) {
    settings || (settings = {});
    settings = $.extend({}, defaults, settings);

    this.each(function() {
        if($(this).attr(settings.attribute)) {
            bind_event.apply(this, [settings]);
        }
    });
    return this;
  }
})(jQuery);