Google Analytics: Track PDF links on webpage

Tracking on various links on your webpage is very important from Marketing perspective. It provides up critical information on how success you online campaign is and whether it attracts the intended audience. There are many tools/services available today that enables you to track pages, for instance, Google Analytics. We can leverage such services to a deeper level to even do tracking at page events level. For example, tracking clicks on hyperlinks or to be more specific PDF links on your web page. Below is the sample javascript code to help you track PDF:

(document).ready(function(){
	$('a').each(function(){
		var href;
		if($(this).attr('href') != null)
		{
		    href = $(this).attr('href').toLowerCase().split('.');
		    if( href.length > 1 ){
			    // Checking if this is a PDF link
			    if( href[href.length - 1] == 'pdf' ){
				    $(this).bind('click', function(){ RecordPDFLink($(this)) });
			    }
		    }
		}
	});
});

function RecordPDFLink($l){
	try{
		//"UA-XXXXX-X" is your GA code
		var pageTracker = _gat._createTracker("UA-XXXXX-X");
		pageTracker._trackEvent('PDF', $l.attr('href'));
	}catch(err){}
}

Note: You need to include ga.js & jQuery (mentioned below) to you page for leveraging this code in HEAD section of HTML.

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _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>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

This method can be used as base for tracking on other minute level like a particular url click, download, hover event and so on.

Enjoy!!

(Visited 247 times, 1 visits today)