Google Analytics Custom Event Tracking - Drupal 7


Google Analytics (GA) Allows us to tracking everything into our pages. we could add new events using Drupal JavaScript Behaviors.

Drupal has a module called Google Analytics, this module has already implemented GA common features, then this article will give you a brief step by step to implement a custom GA event using a Drupal javascript behavior.

Add new JavaScript file using current theme

We will create a new javascript file inside current theme, usually those files are living into js folder on root theme, for this case it will be named "googleAnalytics.js", then using theme info file to load it:

scripts[] = googleAnalytics.js

Define Drupal behavior

We go to create a new javascript behavior and double check if GA instance was created by module Google Analytics and implement an event to tracking when someone clicks to "login in" button inside log in form block.

(function($) {
  'use strict';

  Drupal.behaviors.googleAnalytics = {
    attach: function(context, settings) {
      // Make sure that the google analytics event tracking object or the universal analytics tracking function exists
      // if not then exit and don't track
      if(typeof _gaq === 'undefined' && typeof ga === 'undefined'){
        return;
      }

      // Bind click event.
      $('form#user-login-form input[type=submit]').once('googleAnalytics', function(){
          // Execute GA once element is clicked.
          $(this).click(function(){
              ga('send', 'event', {
                  eventCategory: 'Login Click',
                  eventAction: 'Login Form Block'
              });
          });
      });

    }
  };

})(jQuery);

It will be good enough to tracking every click over "Log in" button. It is pretty straight forward example, I hope it could help you.