This is a short guide on putting together a simple-yet-powerful script for tracking custom events in Google Analytics. Whilst there is already a ton of information on the web about Google Analytics and what you can achieve with it, this blog entry is aimed at devs who want to get going quickly with event tracking.

If you’re completely new to Google Analytics, your best bet is to at least read the Google introduction. They also provide documentation to give an overview on Event Tracking.

The rest of this post assumes that you are familiar enough with GA to know about the ga() function and how it can be used to send events.

Note: Google Analytics doesn’t require jQuery, but the examples in this blog do use jQuery for setting up events. It is also assumed you are using the new version of Google Analytics, analytics.js.

Getting started

You’ll need the Google Analytics script defined in your page. If you haven’t done this yet, Google have got you covered.

If using ASP.NET MVC, it’s a good idea to have this in its own view that you can cache the output of. You can also use a configuration setting to determine whether to output the script at all, to avoid enabling Google Analytics on development / test servers, or perhaps to use a different ID in those environments.

Simply adding this script will get page views tracking in Google Analytics.

Creating a custom tracking script

Once you have the default script, you can then add your own javascript to implement additional GA functionality throughout your site.

The following is a skeleton script that you can then expand on:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var mysite = mysite || {};
var mysite.analytics = (function () {
// _Private function
var _setTrackingEvents = function(ga) {
// Custom tracking code to go here...
};
// Public function
var init = function () {
if (typeof ga === 'undefined') {
if (typeof ga_debug !== 'undefined' && ga_debug) {
console.log('Setting up analytics in debug mode.');
ga = function() { console.log(arguments); };
}
else
{
console.log('Google Analytics disabled.');
return;
}
}
_setTrackingEvents(ga);
};
return {
init: init
};
})();

Typically, once this script has been loaded, then, at a suitable point in your site’s code (e.g. after page load), you can call mysite.analytics.init(); to execute the code and setup your events.

If the Google Analytics script hasn’t been added to the page, this script checks to see if there is a ga_debug variable defined. If there is and its value is truthy, the script creates a dummy ga() function that simply logs to the console. This is useful for testing your analytics events without needing a real GA account in place. If the debug value isn’t in place, this script simply doesn’t go any further.

Event Tracking

Right, on to event tracking! As events are simply tracked by calling a function in javascript, they can be associated with almost any user behaviour on a website - this includes clicking on anything on the page, timings between actions, the scrolling of a page, and much more. If you can imagine it, you can likely write it.

Let’s look at some of the events you could create.

First of all, a good piece of advice is to keep your event definitions generic where you can.

Rather than tracking every interaction individually on your site, try to logically group the different types of interaction together and then come up with a method of selecting these elements. This is especially important where you are building a CMS-driven site and the HTML will be generated on the server.

As an example of a poor way of implementing tracking links, look at the following HTML and Javascript:

HTML

1
2
<a id="products-link" href="/products">Products</a>
<a id="contact-link" href="/contact">Contact</a>

Javascript

1
2
3
4
5
6
7
$('#products-link').click(function() {
ga('send', 'event', 'Link', 'Clicked', 'Products');
});
$('#contact-link').click(function() {
ga('send', 'event', 'Link', 'Clicked', 'Contact');
});

Whilst this will track both of the links, it is time consuming to implement, and you’re going to need to expand your analytics script every time you add a new link to the site.

How about this instead?

HTML

1
2
<a data-ga-link href="/products">Products</a>
<a data-ga-link href="/contact">Contact</a>

Javascript

1
2
3
$('[data-ga-link]').click(function() {
ga('send', 'event', 'Link', 'Clicked', $(this).text() );
});

If you prefer, you can use a class selector instead, though using data- attributes helps to keep the classes of your elements simply for styling. You can even drop this method and go for any* click on a link using the a selector, though this is rather indiscriminate. It’s up to you ultimately on what you’re interested in tracking.

The message here though is to try to group the interactions where you can, so your tracking code can be simpler. There are, of course, times where you will want to track specific events that only occur in single places on your site, and that’s ok.

Tracking Examples

Now let’s look at some examples of events you can track.

Use this to track when a user clicks on an email link.

HTML

1
<a href="mailto:[email protected]">Email the team!</a>

Javascript

1
2
3
4
$('a[href^="mailto:"]').click(function() {
var email = $(this).attr('href').replace("mailto:","");
ga('send', 'event', 'Email', 'Link Clicked', email);
});

Tracked result

Category Action Label
Email Link Clicked [email protected]

If you have social media “Share” links that you executing as part of JS, you could also track them through GA events.

HTML

1
2
3
4
<ul class="list-social-nav" data-social-nav>
<li><a href="#" data-social="twitter" class="twitter"><span class="icon icon-twitter"></span></a></li>
<li><a href="#" data-social="facebook" class="facebook"><span class="icon icon-facebook"></span></a></li>
</ul>

Javascript

1
2
3
4
$('[data-social]').click(function() {
var shareType = $(this).data('social');
ga('send', 'event', 'Share', 'Link Clicked', shareType);
});

Tracked result

Category Action Label
Share Link Clicked Facebook

Similar to the example above, a generic link tracking. This however also includes the text of the link, which could prove useful in determining which buttons on your site are resulting in the most clicks.

HTML

1
<a data-ga-link href="/products">View products</a>

Javascript

1
2
3
4
5
$('[data-ga-link]').click(function() {
var linkText = $(this).text();
var linkDestination = $(this).attr('href');
ga('send', 'event', 'Button', 'Clicked', linkText + ' -> ' + linkDestination);
});

Tracked result

Category Action Label
Button Clicked View products -> /products

Header Navigation

This is useful if you have some top-level header navigation that contains links, and you want to track the level of user interaction with these specific links.

If you have a footer, you can apply the same principle but using a separate data element, for example ga-footer-links.

HTML

1
2
3
<ul data-ga-header-links>
<li><a href="/products">Products</a></li>
</ul>

Javascript

1
2
3
4
5
$('[data-ga-header-links] a').click(function() {
var linkText = $(this).text();
var linkDestination = $(this).attr('href');
ga('send', 'event', 'Header', 'Link Clicked', linkText + ' -> ' + linkDestination);
});

Tracked result

Category Action Label
Header Link Clicked Products -> /products

Client-side interactions

You don’t need to restrict your interaction tracking to just page links on the site. You may already have events setup on your site for particular types of functionality, for example a “Show More” button that reveals some hidden content on the page:

HTML

1
2
3
4
<a href="#" data-reveal="#my-hidden-content">Show More</a>
<div id="my-hidden-content" class="hidden">
<!-- Additional content here... -->
</div>

Javascript

1
2
3
$('a[data-reveal]').click(function() {
$( $(this).data('reveal') ).removeClass('hidden');
});

You may be interested in tracking how many users are actually revealing that content. If you want to do this, don’t edit the previously defined event code that implements the reveal; it’s perfectly fine to have multiple events trigger when a button is clicked, and it is much neater to keep your analytics tracking code together in one place. Instead, you can just add another event:

Javascript

1
2
3
4
$('a[data-reveal]').click(function() {
var target = $(this).data('reveal');
ga('send', 'event', 'Show More', 'Clicked', target);
});

The tiny inefficiency here of multiple events is worth it to keep this code much more maintainable.

Tracked result

Category Action Label
Show More Clicked #my-hidden-content

Scroll Events

A simple page-load isn’t really enough to determine how much of your website a user is actually seeing when they visit. For example, are they just viewing the page and immediately leaving, or are they actually scrolling down to see more content? How many of your users do this?

To help capture this sort of information, you can track when and how far a user scrolls on a page. Whilst you can write this code yourself, there is already a small JS library that wraps up the functionality for you - Scroll Depth.

By default, Scroll Depth tracks events for the percentage a user scrolls down the page - firing events at 25%, 50%, 75% and 100%. However, as well as customizing these percentages, you can also specify the IDs of elements on your page and it will fire tracking events when a user scrolls far enough down for that element to become visible. That’s great, as it tells you how many users are actually seeing a specific part of the page you have designed.

Once the script has been included, a typical way to invoke this library would be:

1
2
3
$.scrollDepth({
elements: ['#products', '#buy-now', '#search-results']
});

Using the above skeleton script as an example, the ideal place to execute this would be straight after _setTrackingEvents is called.

Summary

This has been just a few simple examples of event tracking that you can implement on your site. With the flexibility of Javascript, you can create way more sophisticated events than those mentioned here. Hopefully the above provides a useful primer for you if you are just getting started with Google Analytics.