ColdFusion ORM Book

Track downloads and exit links with Google Analytics

Here's some handy code I just wrote for tracking in Google analytics clicked links which go to external sites or link to files which are being downloaded.

<!--- get jQuery from CDN --->
<script type="text/javascript" src=""></script>
<!--- here is the extra link tracking code --->
<script type="text/javascript">
// make sure the Google Analytics object is available
if (typeof _gaq === 'object') {

// listen to clicks
if (this.href.indexOf('mailto:') === 0) {
else if (this.href.match(/\.(pdf|doc|zip|ppt|exe|xls|docx)$/)) {
else if (this.href.match(/\.(avi|mov|wmv|flv|f4v|mp4)$/)) {
else if (this.href.match(/\.(mp3|wav|aac|wmf)$/)) {
else if (!this.href.match(document.domain)) {

// utility function to get the file extension
function listLast( list ){
return list.split('.').pop().toLowerCase();
<!--- This is your normal Google analytics tracking code --->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-123456-0']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

<p>All of these links will be reported in Google analytics when clicked</p>

<li><a href="assets/downloads/myfile.pdf">PDF download</a></li>
<li><a href="">John's Amazon Wish List</a></li>
<li><a href="">mail me</a></li>



  1. Usefull.

    One small improvement i would suggest is to detect enter key ups on links as well and record these as a 'key press'', otherwise your missing out on traffic data.

    Comment by Chris – April 11, 2012
  2. Thanks! I can you use right away!

    Comment by Marcus C. – April 11, 2012

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.

Please subscribe me to any further comments


Wish List

Found something helpful & want to say ’thanks‘? Then visit my Amazon Wish List :)


Recent Posts