Track Events (clicks) using Google Analytics Script

Solution for GTM and without creating events within the GTM-Container itself

Hi all. I’ve found myself in the same spot as many of you: using GTM and trying to get that tutorial/script working. My requirement was, that it works dynamically without the need of creating specific events in the GTM container itself. After some tries I’ve found a good solution with minimal changes to the initial tutorial:

Step 1: You don’t need to use the Google Analytics Integration. You can use the default GTM script in the header (and also the noscript in the footer).

Bildschirmfoto 2021-08-30 um 17.34.23

Step 2: Use this new script.

<script type="text/javascript">
  //GA Event Tracker Script. Licensed under MIT. Free for any use by all. Written by Paul Seal from codeshare.co.uk

  // Get the category, action and label from the element and send it to GA. The action is optional, because mostly it will be a click event.
  var trackClickEvent = function () {
    var EventCategory = this.getAttribute("data-event-category");
    var EventAction = this.getAttribute("data-event-action");
    var EventLabel = this.getAttribute("data-event-label");
    dataLayer.push({'event':'generic_event','eventCategory': EventCategory,'eventAction': EventAction,'eventLabel': EventLabel});
  };

  // Find all of the elements on the page which have the class 'ga-event'
  var elementsToTrack = document.getElementsByClassName("ga-event");

  // Add an event listener to each of the elements you found
  var elementsToTrackLength = elementsToTrack.length;
  for (var i = 0; i < elementsToTrackLength; i++) {
    elementsToTrack[i].addEventListener('click', trackClickEvent, false);
  }
</script>

Please note:

  • What I just changed is I added a dataLayer.push instead of the ga('send'….
  • I write the eventName with a static value “generic_event”. You can also make that value dynamic by using a variable.
  • I removed the eventValue for myself as it is not needed in my case.

Some screenshots with the results in the dataLayer:

Bildschirmfoto 2021-08-30 um 17.52.14

Bildschirmfoto 2021-08-30 um 17.52.21

Bildschirmfoto 2021-08-30 um 17.47.55

Hope this can help some others out! Happy tracking :wave:

3 Likes