Easy Google Analytics Event Tracking-Do it by convention!

Easy Google Analytics Event Tracking-Do it by convention!

Wednesday 5 December 2012

For better or worse, we use a lot of Google Analytics event tracking at JustGiving, let me explain our workflow:

  • PM wants to track feature A
  • PM decides on track event categories and keywords
  • If a JavaScript file exists for that particular feature, we plumb in jQuery selectors and GA “_trackEvent” code
  • If not, we add a file, wire up the selectors, add the file to the bundling system, add the “_trackEvent” code

I’m not sure about you, but after you or your team have done that for say, 10-15 sub-features of a given feature, across several features, across several products, it’s obviously both a drag and a tedious, repetitive process. This kind of repetition sucks, especially for a simple problem, so we fixed it.


EasyEventTracking – a JavaScript “library”


Get the code:
https://github.com/davidwhitney/EasyEventTracking 

It feels slightly embarrassing to call this a library, so I won’t, but we built a little chunk of JavaScript, on top of jQuery, that uses conventions to “auto-track” events by subtly abusing css selectors.

There’s full documentation and source at the GitHub url above, but the simple overview is:

“Add a snippet of JavaScript to your footer, and auto-track events with the css class ‘track’, along with optional HTML5 data attribute overrides”

You need to add a tiny snippet after your usual GA tracking code that looks like this:

  <script type="text/javascript" src="src/EasyEventTracking.js"></script>
  <script type="text/javascript">
  $(function(){
    var tracker = new EasyEventTracking(_gaq, function(trackEvent){
        console.log("Track event was fired: " + trackEvent);
    });
  });

And then the follow examples from the docs will ‘just work’:

<div class="track">
This will track when clicked.
</div>

<div class=“track-mouseover”> This will track when moused over. </div>

<div class=“track” data-action=“action!” data-category=“category-here” data-label=“label-here” data-value=“my-val” data-non-interaction=“true”> This overrides all available parameters using HTML5 data attributes. </div>

That simple. As you can see above, you also get a nice little callback that you can use to “re-track” the event on your server, just in case you need that stuff in more than one place.

So stop! Don’t write event tracking code! It’s entirely tedious! Do it by convention!