Google Analytics event tracking made simple

25 May 2013

Google Analytics lets you to specify up to four arguments when tracking an event: Event Category* (text), Action* (text), Label (text), Value (number), Interaction flag (true/false).

* denotes a mandatory argument.

WARNING! This article applies to an older version of Google Analytics. You may want to upgrade to newer version - see more here.

To track an event you're expected to call _trackEvent function:

// Let's track that user has pressed "Show me more" button somewhere in UI
$('a.show-more').click(function(e) {
    _trackEvent('Buttons', 'Show Me More button click', 'top button', 1);
    // keep calm and carry on
});

This approach is ok if you've got just a couple of buttons, but it gets quite messy if you need to track more. So when faced with this problem, I naturally looked into the available jQuery plugins, but they were either too bloated with features that I didn't need, or required quite elaborate parameter passing.

Wouldn't be great if for every link or a button that you need to track you could do just this:

<!-- Pipe character "|" is used as a separator
     Event specification syntax is: -->
<a href="#the_how"
   data-ga="Event Category|Action|Label|Value|Interaction flag">Show Me!</a>

<!-- Examples: -->

<a href="#just_category_and_name"
   data-ga="Buttons|Logout">Show Me More!</a>

<a href="#category_name_and_label"
   data-ga="Links|FAQ|Botton-left corner">FAQ</a>

<a href="#the_whole_shebang"
   data-ga="Buttons|Show Me More button click|top button|1">Show Me!</a>

It's actually easy to do, and you don't need no bandwidth-sucking, cache-polluting plugins for that. Below is a simple piece of script that will wire all elements containing data-ga attribute to truly yours _trackEvent function:

;(function($) {
    function initGoogleAnalyticsEventTracking() {
        // Let's get all elements with 'data-ga' attribute</p>
        $('[data-ga]').click(function(e) {
            var data = $(e.target).data('ga')
              , eventParams;
            if (typeof data === 'undefined' || typeof _gaq === 'undefined')
                return;
            // Split the text string into an array
            eventParams = data.split('|');
            // 'call' _trackEvent with the obtained parameters
            _gaq.push(['_trackEvent'].concat(eventParams));
        })
    }
    $(document).ready(function() {
        initGoogleAnalyticsEventTracking();
    }
})(jQuery);

I used pipe character "|" as a separator, but you can change that to your liking.

Subscribe and never miss a new article

If you liked this article and want to get more helpful updates - sign up to my mailing list below. I never spam, period.

Subscribe now and get helpful tips on developing .NET apps - never miss a new article.

You can unsubscribe at any time. I'll never share your email with anyone else.