PDF Tracking in Google Analytics
For the past two weeks I’ve been going through the Google Analytics Academy in order to learn everything I can in order to get Google Analytics Certified. Although I’ve learned lots of awesome things, there is one tip that I really wanted to share. That would be how to track PDF files within Google Analytics.
pdfLabel = $(this).attr('href');
pdfOnClick = "_gaq.push(['_trackEvent', 'PDF', 'Download', '" + pdfLabel + "']);";
What’s going on here? In simplest terms, when the page loads, this piece of code loops through all anchor tags that end with pdf in the file “href” attribute and adds an onclick event to it. When the user clicks on one of these anchor tags, the onclick event which will send information to Google Analytics about the PDF. The code above loops through ALL anchor tags on page, this way you do not have to add the onclick event to each one individually. This saves a lot of time for yourself and for any non-html web content users, they don’t have to worry about it.
The same script can be modified to use with other types of files as well; Word, Text, CSV, Excel, etc. I personally plan to go through my previous websites that have PDF files on them and add this script as well as make it part of my default template when I build new sites.