Fix your Google Analytics events in Google Tag Manager

Published on:12th August 2016 By: Jamie Shields

Recently we came across a problem whereby we needed to change a website from using Universal Analytics to using Google Tag Manager (with Google Analytics enabled within). This process is pretty easy and really common, but no one tells you that if you’ve got Universal Analytics events calls scattered throughout your website, these will all break.

The Problem

Got some of this in your JavaScript?

ga('send', 'event', {'eventCategory': 'goal', 'eventAction': 'submit', 'eventLabel': 'contact-form'});

Well then you’re in trouble!

Google doesn’t tell you how to fix these — instead you’ll be pointed to a myriad of documentation on how to set up triggers from within the Google Tag Manager dashboard. This alternative creates a few problems;

  1. We’ve already got all of our events set up and they work fine – why are we changing this now?
  2. You can’t create triggers for everything. In JavaScript you can call an event from anywhere, at any time.
  3. You can’t commit your event changes into source control. (Trust me you’ll need this when marketing ask why the contact form submit goal hasn’t worked since 10:29am March 8th 2015.)
  4. Last but not least, as developers, we like our events in our source code! We don’t want to fiddle with a UI for controlling something that’s programmatic.

The Fix

It turns out that the way to correctly call the ga() event logging function when using GTM is to specify the tracker name with the send command.

var tracker = ga.getAll()[0].get('name');
ga(tracker+'.send', 'event', {'eventCategory': 'goal', 'eventAction': 'submit', 'eventLabel': 'contact-form'});

A Better Way

In light of this we now always implement the following function to handle all of our Google Analytics events.

function logEvent(category, action, label, value)
{
  if(typeof ga === 'function')
  {
    var command = '';
    
    if(typeof google_tag_manager !== 'undefined')
      command = ga.getAll()[0].get('name') + '.';
    
    command += 'send';
      
    ga(command, 'event', {
      'eventCategory': category, 
      'eventAction': action, 
      'eventLabel': label, 
      'eventValue': typeof value === 'undefined' ? 1 : value
    });
  }
  else
    console.log('ga() not defined');  
}

This allows us to simply call logEvent() instead of ga(‘send’, ‘event’, […]) and the event will be dispatched correctly regardless of the Google Analytics implementation.

Update 16/02/18

Since this article was research Google has changed their default analytics function to “gtag()”, and have also changed the parameters again! So make sure to use the correct implementation depending on the age of the codebase you’re working on.