Google Analytics Events in Drupal

Posted By Brad Czerniak on Tuesday, April 16, 2013 - 10:21

It's easy to get Google Analytics set up on your website. For a Drupal site, it's as simple as installing a popular contrib module. Oftentimes, though, your site features on-page interactions that do not register by default to GA, but that you still want to track.

The way to track stuff that happens on pages (without going to a new page) like expanding/collapsing a menu, toggling a slideshow, or opening a modal window is with Events. Google Analytics provides an easy API method for tracking just about any event you'd like.

If the on-page interactions are built using Views or are otherwise not custom-written JavaScript, you may want to investigate a contrib module like Google Analytics Event Tracking. If you've got some scripts and a working knowledge of JavaScript, the following strategy will be useful for structuring your analytics code.

Planning Out Your Events

Events are tracked via four main properties (passed to the method):

  • Category (string)
  • Action (string)
  • Label (string, optional)
  • Value (integer, optional)

It's up to you how exactly you implement these properties. At Commercial Progression we're sticklers for good semantics, so we start from the following guidelines:

  • Category: The region, block, or logical section name containing the event
  • Action:
    1. The JavaScript event name
    2. An accurate description of what happens when the event fires (expand, collapse, etc.)
    3. A verb acting on a sub-section of the Category container
  • Label:
    1. The inner text of the Action's element
    2. A shared piece of text from the Category (when the Category has multiple Actions)
  • Value: A numerical index associated with the Action, when applicable (ex. The time when a video is paused)

The picture at the top of the post shows the typical planning process for implementing events. We whiteboard out a table and fill in the values. Seeing all the events in one place allows us to optimize the Categories, Actions, and Labels. If a particular element on the page has a bunch of actions, it's often useful in GA for all those actions to have the same label.

Create an Abstraction

The GA Event method is straightforward:

  1. _gaq.push(['_trackEvent', Category, Action, Label, Value]);

_gaq is a global variable when GA is inserted on your page. When it isn't, though (perhaps if you restrict GA to anonymous users or only certain pages), trying to call methods on _gaq will likely throw an error in your browser.

In recent projects, we've created a function in our script's scope to abstract away a few things.

  1. /**
  2.  * Wrapper function for Google Analytics events
  3.  */
  4. function ga_event(params) {
  5.   params.splice(0, 0, "_trackEvent");
  6.   if (typeof _gaq === "object") {
  7.     _gaq.push(params);
  8.   }
  9. }

This function:

  1. Makes sure Google Analytics is available on the page
  2. Lets you pass in just the properties (it prepends the first parameter for you)

To use this function, you just pass in an array containing the Category, Action, and so forth. A typical use case would look like this:

  1. ga_event(['Dialog Button', 'Click', $(this).text()]);

Depending on how you structure your JavaScript, this function could just as easily be adapted as a method on an object you use, or as a jQuery plugin if you're so inclined.

Manage your bindings

In many cases, you can just add the function as a one-liner to the events you've already created. In other cases, you may have to listen to an event for the sole purpose of adding an analytics event. For those, there are a few "gotchas" that I'll explain here to save you some time.

There are many factors: the type of (JavaScript) event, the version of jQuery (the event API has changed considerably over time), etc. The following is an example for a click event in jQuery 1.4.4:

  1. // Capture Next and Prev events in Slideshow
  2. $(".flex-direction-nav a").bind('click', function(e){
  3.   if ($(this).hasClass("next")) {
  4.     ga_event(['FP Slideshow', 'Arrow Right']);
  5.   }
  6.   else {
  7.     ga_event(['FP Slideshow', 'Arrow Left']);
  8.   }
  9. });

Note that the example uses .bind() instead of .delegate() (or .on() in later jQuery versions). This is because the event is used solely as a GA event listener; we're not trying to override existing click handlers on the element. Since there is already an event binding for the element, the use of event bubbling can often be ineffective. This handler doesn't return anything or try to prevent default behaviors; that's handled elsewhere.

Often you can implement an interaction using jQuery without having to explicitly worry about the state of the element. A good example of this is the .toggle() method. You can write a click handler to toggle the visibility of another element without having code that checks the visibility of the toggled element:

  1. $('#toggle-button').click(function(e){
  2.   $('#toggled-thing').toggle('slow');
  3. });

When attaching an analytics event to an interaction like this, all of a sudden it's important to know whether the toggle is expanding or collapsing the toggled element:

  1. $('#toggle-button').click(function(e){
  2.   $('#toggled-thing').toggle('slow', function(){
  3.     if ($(this)[0].style.display === 'none') {
  4.       ga_event(['Toggled Thing', 'Collapse']);
  5.     }
  6.     else {
  7.       ga_event(['Toggled Thing', 'Expand']);
  8.     }
  9.   });
  10. });

This is dirty, but it does the trick. Unfortunately, jQuery doesn't pass a boolean to a toggle's complete function, so you have to do the checking manually inside the callback.

tl;dr

With some careful planning and a helper function or two, setting up Google Analytics events in your Drupal site's JavaScript can be really straightforward.

Looking for Drupal experts to optimize your analytics and SEO? Contact us!