Shoora
10/3/2018 - 4:57 AM

GA events

GA events

function gaEventsEventListener() {
  var nodeList = document.querySelectorAll('.ga-event');

  forEach(nodeList, function (index, value) {
    value.addEventListener('click', gaEvent, false);
  });
}

function gaEvent(event) {
  var dataAttrs = this.dataset;
  var eventCategory = dataAttrs['eventCategory'];
  var eventAction = dataAttrs['eventAction'];
  var eventLabel = dataAttrs['eventLabel'];

  if (eventCategory && eventAction && typeof ga === 'function') {
    ga('send', {
      hitType: 'event',
      eventCategory: eventCategory, // required
      eventAction: eventAction, // required
      eventLabel: eventLabel,
      // eventValue: eventValue,
      // hitCallback: function() {
      //   console.log('ga Event, category: "' + eventCategory + '", action: "' + eventAction + '", label: "' + eventLabel + '"');
      // }
    });
  }
}

document.addEventListener('DOMContentLoaded', gaEventsEventListener);
// https://developers.google.com/analytics/devguides/collection/analyticsjs/events

/*
<%= link_to 'link', 'location', class: 'ga-event', data: { event_category: 'Navigation', event_action: 'click', event_label: 'Our Roots' } %>
*/

$(document).on('click', '.ga-event', function(e) {
  var eventCategory = $(this).data('event-category');
  var eventAction = $(this).data('event-action');
  var eventLabel = $(this).data('event-label');
  // var eventValue = $(this).data('event-value');
  
  // Analytics
  if (eventCategory && eventAction && typeof ga === 'function') {
    ga('send', {
      hitType: 'event',
      eventCategory: eventCategory, // required
      eventAction: eventAction, // required
      eventLabel: eventLabel,
      // eventValue: eventValue,
      // hitCallback: function() {
      //   console.log('ga Event, category: "' + eventCategory + '", action: "' + eventAction + '", label: "' + eventLabel + '"');
      // }
    });
  }
  
  // gtag
  if (eventCategory && eventAction && typeof ga === 'function') {
    // https://stackoverflow.com/a/29434548
    var trackerName = ga.getAll()[0].get('name');
    ga(trackerName + '.send', {
      hitType: 'event',
      eventCategory: eventCategory, // required
      eventAction: eventAction, // required
      eventLabel: eventLabel,
      transport: 'beacon',
      // eventValue: eventValue,
      // hitCallback: function() {
      //   console.log('ga Event, category: "' + eventCategory + '", action: "' + eventAction + '", label: "' + eventLabel + '"');
      // }
    });
  }
});