Tracking Links in Google Analyitcs

When google analytics site instance is created you are given the tracking code that can be placed in the master page (or global template) so that it appears on every page and tracks the page views in your site.

However sometime it is required to track other events, such as click events or PDF downloads. This can be done easily enough by using the following code (that requires Jquery ref).

Step 1 – Add Google Analytics code to the global.js file

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-000000-1']);
  _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>

Step 2 – Add a ref to JQuery

<script type="text/javascript" src="jquery-1.2.6.js"></script>

Step 3 – Add the following additional tracking functions to the JS file. This basically calls the recordevent function everytime links with the “jsTrackClick” class is present. And this functions records the event in Google Analytics

function recordEvent(type, category, label)

{
   _gaq.push(['_trackEvent', type, category, label]);
}
function recordPageView(url) 
{
    _gaq.push('_trackPageview', url);
}
$(document).ready(function() 
{
    $('a.jsTrackClick').click(function () {
        var gaCat = $j(this).attr("gaCat");
        var url = $(this).attr('href');
        recordEvent(gaCat, "Click", url)  
    });      
});

Step 4 – Change HTML links to be tracked by adding the class=”jsTrackclick”

<a href="/doc123.pdf" gaCat="TravelDocs" gaCat="TravelDocs">Download Yatch</a>
<a  href="/doc89.pdf" gaCat="TravelDocs" gaCat="TravelDocs">Download Ski</a>

Step 5 – Check it works in Google Analytics

One thought on “Tracking Links in Google Analyitcs

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>