You are currently offline, so some features of this site may not work fully.

Your browser doesn’t support some of the latest CSS features used to build this site.

Read more about my usage of new CSS features.

A quick tip to help get the most out of user behaviour tracking with Google Analytics.

Tracking Custom Events

Right so I’ve been doing tons of work with Google Analytics lately, implementing custom event trackers to get the most out of user behaviour tracking.

I couldn’t find an easy guide to start implementing the custom trackers anywhere so I thought I’d write a few snippets here to get you going.

I’ll to assume at this point that you’ve installed and have been using the Google Analytics tracking code in your site. If not, go and do it right now! Here’s how.

The gist of it

To implement the custom trackers I wrapped ga( ) in another method with a quick check to ensure the Google Analytics code has been initialised, and only return if it has. This is so that on the local and demo environments it doesn’t throw an error and prevent execution of what else you actually want the event listener to do.

// Wrap it so if GA is not initialised it doesn't go 'undefined'!
function analytics_custom_event_tracker(name, event, label) {
  if (typeof ga === 'function') {
    return ga('send', 'event', name, event, label);
  }
}

// Attach it to a standard JavaScript event listener
var clickMe = document.getElementById('click-me');
clickMe.addEventListener('change', function () {
  // your code goodness

  analytics_custom_event_tracker('Dans Event Listener', 'click', clickMe.value);
  // Sending the value of element to Google Analytics on a click event with the name 'Dans Event Listener'
}, false);

// Attach it to a standard jQuery event listener
$('#click-me').on({
  click: function () {
    // the rest of your magic

    analytics_custom_event_tracker('Dans Event Listener', 'click', $(this).val()));
    // Sending the value of element to Google Analytics on a click event with the name 'Dans Event Listener'
  }
});

Simples

So now all you need to do is call analytics_custom_event_tracker( ) passing in the name to track, the event (click, change etc) and a label - you’ll see where that comes in shortly.

Monitoring events

To see how these events are doing head to Google Analytics and go to Behaviour - Events - Overview.

A screenshot of the Google Analytics menu - events overview
Google Analytics menu - events overview

Head to the overview and you’re all set up to track in depth custom events, using the name and label you set earlier on.

A screenshot of the Google Analytics events overview
Google Analytics events overview

TL;DR

Take the above code snippet and use it to track custom events in Google Analytics.

Let me know what you use them for, there could be some interesting uses out there!