drconsolidated
11/14/2019 - 12:11 AM

Segment Button and Link Tracking with Classes

From: https://medium.com/alpin-io/how-to-integrate-click-events-between-segment-google-analytics-wordpress-c6ac1686f66

To use, add to page beneath Segment code, either directly in theme or in Google Tag Manager.

Replace "ima-segment-" if you want to use a different prefix.

To track events, add classes, starting with that prefixes per the following pattern:

Event: ima-segment-event-

Category: ima-segment-category-

Category: ima-segment-action-

Label: ima-segment-label-

Event Naming Conventions:

  • Event Category: name of the group of similar events you want to track. -- Examples: Downloads, Outbound Links or YouTube Videos. Always use the “plural” form to keep your category names consistent.
  • Event Action: name of the type of event you want to track for a particular element on your website. -- Example embedded YouTube Video: play, pause, 0%, 25%, 50%, 75% or 100%.
  • Event Label: name of the web page element, whose users’ interaction you want to track. -- Example embedded YouTube Video: [Title of the video].
<script type="text/javascript">
  (function(){
  analytics.page();
  document.addEventListener("DOMContentLoaded", function (event) {
    var elements = $("*[class*='ima-segment-']")
      .each(function(index) {
        var segmentData = {};
        $(this).attr('class').split(' ').filter(function(value) {
          var splitClass = value.split('-');
          splitClass.splice(0, 2).join('-');
          if (splitClass[0] === "event") {
           splitClass.splice(0, 1);
           segmentData['event'] = splitClass.join('-');
          } else if (splitClass[0] === "category") {
           splitClass.splice(0, 1);
           segmentData['category'] = splitClass.join('-');
          } else if (splitClass[0] === "label") {
           splitClass.splice(0, 1);
           segmentData['label'] = splitClass.join('-');
          }
        });
        analytics.trackClick($(this), segmentData.event, {
          category: segmentData.category,
          label: segmentData.label
        });
      });
    });
  })();
</script>