How to Track JavaScript and Ajax Events with Google Analytics

Hands up if you use Google Analytics. Actually, it’s probably easier to ask who doesn’t use Analytics. Whatever your opinion of Google and its plans for world domination, Analytics is an amazing tool that has revolutionized web statistics.

For most tasks, the standard page-tracking code is adequate:


<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']); // your ID/profile
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>

That’s great, but what about JavaScript-heavy web applications? The most extreme examples will use a single HTML page, yet provide a range of client-side functionality, event handlers, and Ajaxy loveliness. Alternatively, you may simply want to track document downloads or other activities which do not involve a normal page load.

Identify Your Requirements

Let’s assume we’re creating a JavaScript-powered application that allows the user to search for and download free MP3s.

Note: Ecommerce Transactions

Google Analytics also provides comprehensive ecommerce tracking systems. This is more appropriate for when you’re selling items, so keep reading sitepoint.com for a tutorial coming soon.

The Category
The first data item to consider is the category—a single name for all events of a particular type. In this case, we could use “mp3system.” You could use the same category name for every event on your web page, or different categories, depending on the widget being used.

Actions
An action is a task completed by the user or, on a technical level, an activity that results in a JavaScript event being fired. For our system, we could monitor:

  • search (searching for a song using a key phrase)
  • view (viewing information about an MP3)
  • download (starting an MP3 download)

Labels (optional)
A label is an optional description of the action that occurred. In the case of searching, we could use the search phrase as our label. For viewing or downloading, we could apply the song ID and/or title for our label.

Values (optional)
The optional value provides a numeric quantity for the event. For MP3s, we might provide the file size or track length, so that we can report total and average download statistics. In other situations, you could record a monetary amount, or the time taken to complete an action.

The Code

That’s enough planning; let’s look at the JavaScript tracking code:


if (_gaq) _gaq.push(['_trackEvent', category, action, label, value]);

Simple. The condition first checks that we have included the Analytics JavaScript, then sends the details of the event itself. Typical events from our MP3 system might be:


_gaq.push(['_trackEvent', 'mp3system', 'search', 'good songs']);
_gaq.push(['_trackEvent', 'mp3system', 'view', 'song 1', 3456]);
_gaq.push(['_trackEvent', 'mp3system', 'download', 'song 1', 3456]);

For a file download, the simplest HTML would be:


<a href="file.mp3" onclick="_gaq.push(['_trackEvent', 'mp3system', 'download', 'file.mp3']);return true;">download</a>

Google Analytics event trackingYour custom event statistics should be available on Google Analytics within 24 hours. From your profile, select Content followed by Event Tracking.

Google Analytics event tracking can help you monitor user activity at a deeper level than standard page views. Are you using it for any interesting applications? Will you implement the code in your next project?

note:Want more?

If you want to read more from Craig, subscribe to our weekly tech geek newsletter, Tech Times.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • WASP

    You can use WASP (Web Analytics Solution Profiler) to check if the trigger are done right away as you fire the events and see if the proper data is being sent out

  • http://www.fxcbs.com fxcbsar

    Thanks for posting about this.
    I like this blog and i well viset agen thank you
    Good luck

  • http://fcOnTheWeb.com ferrari_chris

    Good to know. I’m going to look at implementing this in a our current project where we have some 3rd party HTML samples that we can’t modify to add tracking code, but now I know we can track when they’re launched.
    Sweet!

  • blog.codehangover.com
  • BrenFM

    Seems we’re just scratching the surface on Google Analytics. Thanks for the extremely informative post… opened up a fairly large (and exciting/interesting) range of opportunities for us!

  • dusoft

    Yes, we are using to track form inputs and to see what are the form fields the most users choose to leave the page at…

  • robertcfi

    Great post. Very good code and explanation. It would be awesome to track which javascript codes are getting hit.
    Thank you

  • Jayesh

    Easy to understand tutorial
    And by using this tutorial i have implemented this tracking feature in my website http://www.3cci.in.
    Now i will be able to track virtual page view.
    well google analytics is so power full and a bit complicated.
    Thanks,
    http://www.3cci.in

  • Darren884

    Thanks for this awesome tutorial. I never knew you could do this! This changes the whole game and makes it easier to know how users are interacting!

  • http://iconreproductions.com Miro2112

    Sweet – I’ve been looking for a way to track my users who use the search function…sounds like this is it!

    • http://www.optimalworks.net/ Craig Buckler

      Actually Miro, Analytics provides specific functionality to track search (stay tuned for details). Unless your search is handled by Ajax requests, it may be best to use that instead.