Event Analytics

The developer friendly javascript library to do Event Tracking using Google Analytics or Piwik

Author: Fabio Buda fabiobuda@netd.it
Copyright 2015 Netdesign

First doc release: Oct 26 2015
Last doc revision: Nov 03 2015

EventAnalytics.js logo

1. What is Event Analytics?

Theory – Event Tracking and Analytics use cases

Event Analytics is a common practice to get richer insights into your web analytics engine. Both Google Analytics and Piwik support advanced API to register custom events and variables based on custom conditions or algorithms. If you develop or install some Event Analytics integration for your website, your marketing department would get more fine-grained information about visitors and their interaction with your content and more in general with your whole User Interface will be more specific.

This jump ahead could help your business to identify better your online target allowing you to plan a more sophisticated web strategy. All big web corporations (Google, Facebook, Amazon) normally use this kind of tools yet and EventAnalytics.js library aims to help the global webmaster and developers community to gain freely and easily more information about visitor interactions.

Practice – EventAnalytics.js

As we just said, Google Analytics and Piwik both offer functions and features to register special events but in practice you will run into spaghetti-javascript having to manually bind user actions in the UI with the analytics engine. Some websites offer online tools to simply configure some <...onclick=”ohmy('fuc**** inline code!');”..> but this is generally a bad option if you want to track events for a complex and button-rich user interface. See how this bad online tools work: Raventools - Event Tracking Code for Google Universal Analytics.

1.1 How EventAnalytics.js helps

What is EventAnalytics.js library?

EventAnalytics.js is a lightweight open source (less than 7Kb when minified) javascript library that once installed on a web page will automatically track many useful events. EventAnalytics also simplifies the way the developer attach new Analytics Events to the user visit.

1.1.1 Features:

1.1.2 Examples:

Suppose you want to track how your visitors interact with your top folding menu


EventAnalytics.RegisterDOMEvent(
"a.my-top-foldmenu", "click", "FoldTopMenu", "open", "%content"
);

Note that “%content” is a variable name to specify how to label the event. See ParseNameVariables( obj:event, str:varname ) documentation for more details.

Suppose you want to track how your visitors interact with your breadcrumb menu. In this case you'll need to store the event data in the next pageview, an action that could be done calling LateRegisterDOMEvent().


EventAnalytics.LateRegisterDOMEvent(
"div.breadcrumbs a", "click", "Breadcrumbs", "click", "%content"
);

Suppose you want to track all visitor interaction with an input form (focus and digit):


EventAnalytics.TrackFormInteraction();

Remember to add the class 'EventAnalytics' to your form to activate the tracking. NOTE: EventAnalytics is able to track only one form per page, if you want to register events for some other forms you should use the EventAnalytics.RegisterDOMEvent() using the onsubmit event.

  1.1.3 Important notices for self-hosted Piwik users

If you use the Piwik Analytics engine in a self managed web server you should add the following configuration to the used VirtualHost, Directory or .htaccess(*):


Header set Access-Control-Allow-Origin *

Without this header some browser (such as Internet Explorer 10) will not download the Piwik engine and will not track users. EventAnalytics will also stop working.

If you use a cloud service or a shared hosting and you can't add .htaccess for your Piwik installation ask to your technical support.

(*) Is widely known that .htaccess parsing is an unnecessary overhead. If you have complete access to your webserver configuration you will add the Header directive in the VirtualHost or Directory configuration block.

  1.1.4 Important notices for Google Analytics users

EventAnalytics.js is able to use the (relatively) new Google “analytics.js” but is not compatible with “ga.js”. If you use the old “ga.js” you should seriously consider to upgrade to Universal Analytics. See the Google Analytics documentation to know how to upgrade your javascript engine.

Google Universal Analytics does not seem to be officially documented about the visitor info, some forum posts says to parse the “_ga” cookie to discover the number of visits but is not documented how often the number of visits value is updated. In EventAnalytics.js we choose to determine if the user is new or returning only if the cookie is created more than 2 hours before. To discover the timestamp of cookie creation we have followed an unofficial documentation of the Universal Analytics _ga cookie field values.

2. How to install

To install and use EventAnalytics.js you have to meet these dependencies:

To install EventAnalytics.js you have to install the EventAnalytics.js script and set up a custom function on the onload attribute of your analytics code snippet on all pages. Call a custom function on the script.onload event makes sure that Piwik or Google Analytics are already loaded. Examples:

First thing, define your CustomInitFunction in a script before your analytics engine tracking code


function CustomInitFunction(){
    EventAnalytics.Init();
    EventAnalytics.RegisterDOMEvent("span.tab-button", "click", "Tab", "show", "%content"); 
    EventAnalytics.RegisterDOMEvent("a.action-open", "click", "TopMenu", "openmenu", "%title");
}

Then, you should set CustomInitFunction as a callback in the onload attribute of your async analytic script element. Remember that your onload attribute must be set BEFORE the src attribute, otherwise your onload callback will never be call.


<script type="text/javascript">
  <!-- PIWIK -->
  var _paq = _paq || []; 
  _paq.push(['trackPageView']); 
  _paq.push(['enableLinkTracking']); 
  (function() { 
    var u="//analytics.example.com/"; 
    _paq.push(['setTrackerUrl', u+'piwik.php']); 
    _paq.push(['setSiteId', 1111]); 
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; 
    g.type='text/javascript'; g.onload=CustomInitFunction; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); 
  })(); 
</script>


<script>
  <!-- GOOGLE ANALYTICS -->
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 
  m=s.getElementsByTagName(o)[0];a.async=1;a.onload=CustomInitFunction;a.src=g;m.parentNode.insertBefore(a,m) 
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 
  ga('create', 'UA-XXXXXXX-X', 'auto'); 
  ga('require', 'displayfeatures') 
  ga('send', 'pageview'); 
</script>

3. Design guide

EventAnalytics.js is designed to be light as much as possible to be loaded and to be as much as possible sustainable in computation workload. EventAnalytics.js gives the opportunity to start tracking UI interactions without sacrifice the user experience. All the link.onclick and form.onsubmit events are tracked without storing the information soon after the user interaction. All the information is stored in the next pageview, this way working is typical of EventAnalytics, and it is important because it helps you to avoid to impact on the responsiveness of your website or of your web application, this is why Event Analytics is able to track all strategic user interactions.

3.1 Notes about event tracking on page change

When you have to track any user interaction event with a link <a href='...'></a> or with a form <form></form> html element you have only the following four options to make data persist before the browser starts loading the new page URL:

  1. Attach a callback to the link returning false on the onlick event, then store the data with an AJAX request, wait a prefixed amount of time (~300ms) and only at the end redirect the visitor to the previously clicked URL – Example: $(“a”).on(“click”, function(){DoSomethingUseful(); setTimeout(...); return false;})
  2. Store the data in LocalStorage (needs solution #4 Cookie as a polyfill backend)
  3. Alter the href attribute of the link to pass the useful information to the next pageview as an hash (useful only for links not having #hashes in their hrefs)
  4. Store the data in a short-life cookie (using a < 150ms delay)

Every option could be useful and profitable for EventAnalytics.js but we have choosen to produce a minimal impact on the UI so we had prefer points 3 and 4 that we have converted to API calls:


EventAnalytics.LateRegisterDOMEvent()

and


EventAnalytics.DelayRegisterDOMEvent()

4. Reference guide

In this section are documented all EventAnalytics API calls

EventAnalytics.js UML schema

IMPORTANT NOTICE: EventAnalytics.js uses jQuery for event handling and element selection. You should consider all “selector” variables in function signatures as jQuery selectors. Both “li.menu a” and “div.tabs span.tab” and “#foobar” are all allowed selectors.

Init()

Checks if exists Piwik or Google Analytics and executes all the other init calls

RegisterNewVisitorCallback( function:callback, int:delay=25 )

Registers a callback function and executes it, after a fixed delay (milliseconds), if only the user is a new visitor

RegisterReturningVisitorCallback( function:callback, int:delay=25 )

Registers a callback function and executes it, after a fixed delay (milliseconds), if only the user is a returning visitor

RegisterLateEventData()

Checks if any Late event exist. Stores it in the Analytics engine

RegisterDelayEventData()

Checks if any Delay event exist. Stores it in the Analytics engine

InitScrollEvents()

Initialize the scroll event handling

InitVisitor()

Initialize the available visitor information

RegisterUIEvent( str:category, str:action, str:name, [int:value] )

Sends an event to the used Analytics engine

ParseNameVariables( obj:event, str:varname )
If varname is %title, %content, %parenttitle, %parentcontent this function returns title or content from the element or its parent otherwise returns the varname itself. This function is used in all *RegisterDOMEvent methods
RegisterDOMEvent( str:selector, str:bindevent, str:category, str:action, str:name, int:value )

Store an event where an event “bindevent” is triggered on element $(“selector”). Store the event using the “category”, “action”, “name” and “value” in the anayltics engine. NOTE: the “name” variable could be a placeholder for “%content”, “%title”, “%parentcontent”, “%parenttitle”

LateRegisterDOMEvent( str:selector, str:bindevent, str:category, str:action, str:name, int:value )

Store an event in the next pageview and with no UI delay when an event “bindevent” is triggered on element $(“selector”). Store the event using the “category”, “action”, “name” and “value” in the anayltics engine. NOTE: the “name” variable could be a placeholder for “%content”, “%title”, “%parentcontent”, “%parenttitle”

DelayRegisterDOMEvent( str:selector, str:bindevent, str:category, str:action, str:name, int:value )

Store an event in the next pageview with minmal UI delay (125ms) when an event “bindevent” is triggered on element $(“selector”). Store the event using the “category”, “action”, “name” and “value” in the anayltics engine. NOTE: the “name” variable could be a placeholder for “%content”, “%title”, “%parentcontent”, “%parenttitle”

TrackFormInteraction()

Tracks user interaction with all visible input elements of a single <form> per page. To start tracking it, you should add the class “.EventAnalytics” to the form html element

RegisterInputFieldEvent( obj:input )

Tracks user interaction (focus, digit) with a single <input> element in a tracked form attaching event functions. This function gets the event label from input placeholder attribute. If the placeholder attributes does not exist, it gets the value from a <label for="inputID"/> text content. If your event reports does not contain text label for an input interaction you should check your input attribute or connected label

InputInteractionDetectorCallback( obj:event )

This function is triggered after an input interaction (focus, digit) and it stores the event data in the used analytics engine

5. Download

In this section you can download all EventAnalytics.js sources.

Download EventAnalytics.js 1.0
Released on Nov 03 2015

GPL License

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

6. Commercial support

If you need commercial support to setup, configure, optimize or analyze your online event tracking analytics you could contact us to ask for a quote. We are a Web marketing agency located in Carlentini, Italy and we can offer you a wide range of services for your online marketing and analytics projects. Contact us, our mail address is info@netd.it.

7. Copyrights holders

The name EventAnalytics is property of Netdesign (Our full official website is available - in italian - going to Netdesign).
The name Google Analytics is property of Google Inc.
The name Piwik is property of Piwik.org.
The name jQuery is property of The jQuery Foundation.

8. Privacy

When you track your visitors using one of the available analytics engines you have to notice to your users that your website is using technologies to track and analyze their behaviour. This is a fair action for your users and in some jurisdictions this action is mandatory (as defined in the European Cookie Law).

9. Fork on Github

All EventAnalytics source code is available on Github, fork Event Analytics on Github now!.