Google Analytics click event tracking with jQuery

This post will be showing you how to use jQuery to trigger Google Analytics event tracking.

Here is an example of a script to track PDF download clicks.

<a href="#" onClick="_gaq.push(['_trackEvent', 'PDF', 'Download', 'Document name']);" title="Download Document name">Download</a>

Every time user clicks this Download link, it tracks it as an event in Google Analytics.

The above method would work well for one link. But, if you have a lot of links to track, it is time to use jQuery and CSS to simplify the process.

Firstly, we use CSS class (.pdf) with the link. It will look like:

<a href="#" class="pdf" title="Download document name">Download</a>

Next, use jQuery to execute event tracking, each time the link is clicked.

<script type="text/javascript">
 $(document).ready(function(){
   $('.pdf').click(function(){
     _gaq.push(['_trackEvent', 'PDF Download', 'Click', 'Document name']);
   });
 });
</script>

Now, we use the link's title attribute to pass the document name of link so we can track it on Google Analytics.

<script type="text/javascript">
 $(document).ready(function(){
   $('.pdf').click(function(){
     _gaq.push(['_trackEvent', 'PDF Download', 'Click', $(this).attr('title')]);
   });
 });
</script>

By using jQuery, it makes life much easier when you try to track the outbound links or user’s action through Google Analytics.