Tuesday 16 February 2010

Using Analytics to Track Events & AJAX Navigation

Google Analytics is THE way to record and analyse everything about the traffic on your site. Whilst it's real easy to setup you need to change the default behaviour if you want to record javascript events and AJAX navigation changes; this is how to do exactly that.

Analytics requires two things to work. You need the Analytics resource on the client...

<script type="text/javascript">
   var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
   document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
...and call the tracker with your unique ID (provided when you sign up)...
<script type="text/javascript">
   try {
      var pageTracker = _gat._getTracker("123456789");
      pageTracker._trackPageview();
   } catch (err) { }
</script>
...it's the pageTracker._trackPageview(); part that sends the data to Google Analytics. Without parameters the current URL is sent. However, you can override the default behaviour and pass the URL as an argument.

So change the second part to...

<script type="text/javascript">
   try {
      var pageTracker = _gat._getTracker("123456789");
   } catch (err) { }
</script>
...then you can call pageTracker._trackPageview('/My-Virtual-URL'); with your 'virtual' URLs at will - perfect for recording javascript events and AJAX navigation changes :)

2 comments:

  1. Thank you very much! I'm the admin of italian blog skimbu.it, maybe most advanced blog in the world (I implemented ajax navigation, tabbed sidebar and post footer, I introduced the post toolbar in bottom right...) and I'm going to implement this in my blog.
    Thank you

    ReplyDelete
  2. Your post helped me, thank you, buddy!

    ReplyDelete