Google Analytics Custom Event Tracking - Drupal 7

By kenneth, Sun, 12/04/2016 - 02:45

Authored on

Image

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.

Comments

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.