Google Universal Analytics provides a great possibility to track custom events on your website. These feature can be used to analyze special user-interactions with e.g. advertised/highlighted content or social media links. The recorded data can be directly used to optimize your website!

The event tracking is very simple:

To simplify the integration you can implment a simple data-binding which will automatically add event listeners (click) to you DOM elements. Just add an additional attribute to your elements which includes (in this example) a prefix, the event-category and the event-label (scheme: "prefix:category:label").

Example: Social Links with data-binding#

<a href="https://www.facebook.com/groups/" title="Facebook" data-event="ga:social:facebook" class="FacebookButton"></a>
<a href="https://twitter.com/" title="Twitter Stream" data-event="ga:social:twitter" class="TwitterButton"></a>

Finally, we need some javascript to process the additional attributes. You should always check if Google Analytics is enabled (maybe an adblocker is used or an opt-out option is set!) to avoid javascript errors. The following code will send an event to analytics each time a user clicks on the bound elements.

MooTools based Data-Binding#

window.addEvent('domready', function(){
  // GA loaded ? Used to avoid js errors on blocked analytics
  if (typeof ga !== 'function'){
    return;
  }
  
  // event binding
  document.getElements('[data-event]').each(function(el){
    // get event string
    var d = el.get('data-event').split(':');
    
    // format:  "type:category:name"
    if (d.length != 3){
      return;
    }
    
    // extract vars
    var evtType = d[0];
    var evtCategory = d[1];
    var evtName = d[2];
    
    // outgoing link on click event
    el.addEvent('click', function(){
      // universal analytics event ?
      if (evtType == 'ga'){
        ga('send', 'event', evtCategory, 'click', evtName);
      }
    });		
  });
});