I started testing out event tracking with Google Analytics recently. There are two main ways that I’ve tried using it so far:
- Click event added to link
The tracking event requires the following components:
- A category
- An action
- A label
In all three cases, each component can be arbitrary text. So really anything goes. The only warning, particularly regarding categories, is that you have to be consistent about the names you give things. In other words “Database” and “Databases” will be tracked as separate categories.Here is more information about the setup, so far:
The two main features to note are the class name “track” and the “data-ga-category.” The Data element was introduced in HTML5. It can be used to store application/page specific information. In this case, it stores a category name for the tracking event.
The script looks for every link with the “track” class then adds an click event to it that looks like:
It also adds a “tracking” class to the link, so that a tracked link could be styled differently, if desired.
This is the jquery function I created to actually attach the event to the links:
Click Event added to link
An event tracking link in this case should look like:
<a href="http://example.com" onClick="_gaq.push(['_trackEvent', 'category', 'action', 'label'])">Link Text</a>
Note here that the link has an “onClick” event instead of a class and data attribute. The event is baked right in. Also, notice that category, action, and label have single quotes around them. These will have to be typed right into the code, since there’s no way to dynamically create these (well, there could be a way, but I digress…)