Tracking download of non-html (like pdf) downloads with jQuery and Google Analytics

Posted by developerit on Developer IT See other posts from Developer IT or by developerit
Published on Sun, 10 Oct 2010 04:48:08 +0000 Indexed on 2010/12/06 16:58 UTC
Read the original article Hit count: 2794

Hi folks, it’s been quite calm at Developer IT’s this summer since we were all involved in other projects, but we are slowly comming back.

In this post, we will present a simple way of tracking files download with Google Analytics with the help of jQuery. We work for a client that offers a lot of pdf files to download on their web site and wanted to know which one are the most popular. They use Google Analytics for a long time now and we did not want to have a second interface in order to present those stats to our client. So usign IIS logs was not a idea to consider.

Since Google already offers us a splendid web interface and a powerful API, we deceided to hook up simple javascript code into the jQuery click event to notify Analytics that a pdf has been requested.

(function ($) {
    function trackLink(e) {
        var url = $(this).attr('href');
        //alert(url); // for debug purpose
        // old page tracker code
        pageTracker._trackPageview(url);
        // you can use the new one too
        _gaq.push(["_trackPageview",url]);
       //always return true, in order for the browser to continue its job
        return true;
    }

   // When DOM ready
    $(function () {
        // hook up the click event
        $('.pdf-links a').click(trackLink);
    });
})(jQuery);

You can be more presice or even be sure not to miss one click by changing the selector which hooks up the click event. I have been usign this code to track AJAX requests and it works flawlessly.


© Developer IT or respective owner

Related posts about Developer IT

Related posts about Web Development