How to Track Downloads in Google Analytics

How to Track Downloads in Google Analytics

Posted by on Fri, Apr 29, 2011
Filed Under | Google Analytics


UPDATE: Please reference our updated post on tracking downloads and external links.  It is now more efficient and flexible.

Google Analytics uses client-side code (JavaScript) to record pageviews and other interactions (which are then sent as a tracking pixel request to Google’s servers).  This works great for html pages on your website (regardless of the programming language it was developed in) and it even works great for Flash, Silverlight, and other web technologies.

File Downloads

Out of the box, Google Analytics will not track how many times people download PDFs or other file types, simply because those files do not have the ability to request a tracking pixel.  In this blog post, we’ll be covering the ways to properly track file downloads in Google Analytics.

Throughout this blog post, I’ll be assuming that you are wanting to track a PDF download, but keep in mind that you could use this same technique to track the download of a .mp3, .mp4, .xlsx, etc — it really does not matter.  Additionally, I recommend tracking file downloads as events (so that you are not inflating pageviews on your site), but you could very well track them as pageviews.  In the new Google Analytics v5, you can now setup events as goals!

The code you will want to use is different depending on if you are opening the PDF in a new window via target=”_blank” or if you are opening the PDF in the current window.

Tracking PDF Download (in new window/tab)

If you are linking to a PDF that opens in a new window (by using target=”_blank” for example), then the tracking code is fairly simple to implement.

Your link will look something like: <a href=”pdfs/my-file.pdf” target=”_blank”>Download my file</a>

To properly track this in GA, add the following code to link tag:

  • <a href=”pdfs/my-file.pdf” target=”_blank” onclick=”_gaq.push(['_trackEvent','Download','PDF',this.href]);”>Download my file</a>

When a user clicks to download your file, a tracking pixel is requested and recorded in GA’s database.  Problem solved!

Tracking PDF Download (in current window)

If you do not use the link tag’s target attribute to open the PDF in a new window and instead you have it opening in the same window, some browsers will interrupt the tracking request and send the visitor straight to the download.  When this happens, you won’t see the event recorded in GA.

Your link will look something like: <a href=”pdfs/my-file.pdf”>Download my file</a>

To properly track this in GA, add the following code to the link tag:

  • <a href=”pdfs/my-file.pdf” onclick=”var that=this;_gaq.push(['_trackEvent','Download','PDF',this.href]);setTimeout(function(){location.href=that.href;},200);return false;”>Download my file</a>

We have to give the browser enough time to make the request, and this is done by using the setTimeout() javascript function to delay the request by a fraction of a second.  We typically do 200ms (that’s 1/5 of a second), but if you have more requests, you may want to increase this.  You can use debugging tools to understand if you need to increase this value.

Automate It!

If you have a lot of file links on your site or you just don’t want to have to worry about adding this code each time you add a new link, then you can certainly automate the tagging for download tracking.

There are a number of solutions that help you do this and that also provide additional automated tracking functionality.  One of our favorites is Analytics Engine, which is developed by our friends at Analytics Pros (a fellow Google Analytics Certified Partner).  Definitely check out their product to learn more.

Another option is to use the code we’ve provided below.  Note that this code requires the jQuery JavaScript library to be on your pages.

Feel free to customize this code.  It can be placed in its own .js file and should be placed in the <head> on each of your pages.  This script automates the following:

  • Tracks file downloads as events for the following extensions: .zip, .exe, .pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3 (again feel free to modify the list)
  • Tracks outbound clicks as events if the href value contains http:// or https:// and the domain value doesn’t match the current domain
  • Tracks mailto email clicks
<script type="text/javascript">
if (typeof jQuery != 'undefined') {
	jQuery(document).ready(function($) {
		var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
		var baseHref = '';
		if (jQuery('base').attr('href') != undefined)
			baseHref = jQuery('base').attr('href');
		jQuery('a').each(function() {
			var href = jQuery(this).attr('href');
			if (href && (href.match(/^https?\:/i)) && (!href.match(document.domain))) {
				jQuery(this).click(function() {
					var extLink = href.replace(/^https?\:\/\//i, '');
					_gaq.push(['_trackEvent', 'External', 'Click', extLink]);
					if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
						setTimeout(function() { location.href = href; }, 200);
						return false;
					}
				});
			}
			else if (href && href.match(/^mailto\:/i)) {
				jQuery(this).click(function() {
					var mailLink = href.replace(/^mailto\:/i, '');
					_gaq.push(['_trackEvent', 'Email', 'Click', mailLink]);
				});
			}
			else if (href && href.match(filetypes)) {
				jQuery(this).click(function() {
					var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
					var filePath = href;
					_gaq.push(['_trackEvent', 'Download', 'Click-' + extension, filePath]);
					if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
						setTimeout(function() { location.href = baseHref + href; }, 200);
						return false;
					}
				});
			}
		});
	});
}
</script>

The script detects to see if you are opening the file in a new window or not and automatically uses setTimeout() for 200ms if you are not.  If you have multiple tracking objects on a page or have a named tracker, then you’ll want to customize this script.  This script uses the asynchronous ga.js tagging syntax.

Bounce Rate Impact on Tracking File Downloads

When you fire event tracking or a virtual pageview, this will impact your bounce metric in a positive direction.  Events and pageviews count as an interaction.  If you have more than one interaction (pageview or event), then that visit is not counted as a bounce.  Since the visitor took some action on the site, they should not be counted as a bounce anyways, so by coding your file download links, you are actually increasing the accuracy of your metrics.

Enjoy this post?

Join the discussion below, subscribe to our RSS feed or share it on the web.

This post was written by:

has written 31 posts on the Web Analytics Blog.

Joe is the Analytics Director and a Partner at Blast Analytics & Marketing. He understands Google Analytics like nobody else and is a master of many programming languages.

Add Joe to your circles on Google+


Tags: , , ,
  • http://byjoeybaker.com/ Joey Baker

    Hmm… I think I’ve got a cleaner (jquery only) way of accomplishing this:

    $(‘[href$="pdf"]‘).live(“click”, function(){ // get the link attribute and find the filename of the PDF var pdfLink = $(this).attr(“href”), pdfLocation = pdfLink.substr(pdfLink.lastIndexOf(“/”)).replace(“/”,””) ; _gaq.push(['_trackPageview', pdfLocation]); });

  • http://www.blastam.com/broadcast Blast Advanced Media

    @joeybaker:disqus

    Thanks for sharing your code! You’ve provided much simpler code for the specific purpose of tracking PDFs. It looks like it would work fine with the following caveats:

    -It only works with PDF file types.

    -It does not automate the delay click if you do not have your link opening in a new tab/window.

    Additionally, I personally like to use event tracking for PDFs (easy to change in your code above of course).

    Thanks,

    Joe

  • http://byjoeybaker.com/ Joey Baker

    Sure thing. It should be pretty straight forward to modify it to accept additional file types:

    $(‘[href$="pdf"]‘), [href$="exe"], [href$="pdf"]‘).live(…

    not sure what you mean by the delay click?

  • http://www.blastam.com/broadcast Blast Advanced Media

    You’ll notice that I use setTimeout() to delay the click by 200ms. Certain browsers, like Chrome for example, will interrupt the GA tracking pixel request when you click the link (AKA a race condition). In my code, I check to see if target=”_blank” is being used and if not, then I delay the request.

    Thanks,

    Joe

  • http://claudiusgunter.com Claudius

    Hi there, thought I’d mention that some users might not know that they need to make sure the quote characters are correct (as wordpress changes these automatically to the curly type quotes)

  • http://profiles.google.com/kevin.blount Kevin Blount

    Many thanks for the article. I’m just wondering: is there a specific version of jQuery that the code you provided requires?

    I ask, because I just added the code to a test page, and forgot to reference jQuery. Oddly, no errors in FF 3.6.17. I then downloaded and added a reference to jquery-1.6.min.js on my page, and now I get an error: “jQuery(this).attr(“target”) is undefined.”.

    The link for the download is “Download Software” – shouldn’t be anything wrong with that, I don’t think (obvious spaces removed in live html)

    Any help would be greatly appreciated :)

    Kevin

  • http://www.blastam.com/broadcast Blast Advanced Media

    Hi Kevin,

    There is an issue with the new release of jQuery v1.6 and the code I’ve provided. Specifically, they’ve changed the .attr() to return undefined if the value is not set, where in previous versions, this was not an issue.

    I’ve updated the code in this post to reflect this change. You need to change the two lines that reference .attr(‘target’) to the following:

    if

    (jQuery(this).attr(‘target’) != undefined && jQuery(
    this
    ).attr(
    ‘target’
    ).toLowerCase() !=
    ‘_blank’
    ) {

    Thanks,

    Joe

  • http://profiles.google.com/kevin.blount Kevin Blount

    Thank you so much for that speedy update. I can confirm no more errors in the FF console. Now to test for a day or two, then see if I can find the tracking info in GA :)

  • Chris Sacco

    Hey Joe, just wondering….What is the purpose of “this.href”? Is it necessary to track PDF downloads in new windows?

  • http://www.blastam.com/broadcast Blast Advanced Media

    Hi Chris, the “this.href” references the a tag’s href attribute value.  So instead of manually passing in the href value inside the _gaq.push() call, I find it easier to just reference it this way (less work and you can easily copy/paste).  You can of course take that out and specify what you want inside the _trackEvent call.

    Thanks,
    Joe

  • Chris Sacco

     Thanks Joe. Good stuff

  • Mmarquis

    Can someone help me figure out how to track a PDF download when the link is in an e-mail and not the website where the UA code is?

    I’ve looked everywhere and can’t seem to find a solution.  Thanks!!

  • http://www.blastam.com/broadcast Blast Advanced Media

    You won’t be able to directly track PDF downloads when linked from an email (since an email can’t execute JS and a PDF itself can’t execute JS).  The optimal way to handle this is to bring the user to a regular page URL (and use campaign tags from the email) and then offer a download link/button.

    Thanks,
    Joe

  • Sunshine

    We use a CMS which automatically appends an “.aspx” extension to the end of all file downloads — yeah, I know it’s weird and silly, but we can’t do anything about it. So for example you get URLs like:
    http://www.example.com/docs/hello.pdf.aspx

    Would this script trigger a Download event when clicking on URLs like this?

  • http://www.blastam.com/broadcast Blast Advanced Media

    The script I’ve provided will not trigger a download event on a URL that matches your provided structure.  The script only grabs the last extension of ‘.aspx’ in your example.  You can certainly extend this script to work in your unique environment though.

    You’d have to rewrite the line that contains the following code:
    href.match(filetypes)

    and then also the line that has the following code:var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;

    Hope that helps!
    Joe

  • Sunshine

    Thanks very much Joe, it took me a few tries but I managed to modify your script to get it working with the weird .pdf.aspx extensions etc.

    For the benefit of others who might be in the same situation as me, these are the lines I changed:

        var filetypes = /.(zip|exe|pdf|doc*|xls*|ppt*|mp3).aspx$/i;

                    var    hrefWithoutASPX = href.replace(“.aspx”, “”);    // need to strip out the .aspx at end of URL
                    var extension = (/[.]/.exec(hrefWithoutASPX)) ? /[^.]+$/.exec(hrefWithoutASPX) : undefined;

  • MitchellT

    Hello – thanks for this blog post and the code samples.  The tag isn’t working for me, does it matter if the main Google Analytics tag is at the top or the bottom of my html?  Right now it is just above the body tag.

  • http://www.auto-my.ro/piese-auto piese auto

    It is good to know how many people want your work even if it is in PDF mode. But i try to put this code and i can do it. I really do not know why.

  • http://www.blastam.com/broadcast Blast Advanced Media

    This code is not specific to PDF tracking and can be extended or easily accomplished using the automated method I mentioned.  If you want to share more details about your implementation, I can provide additional input on getting it to work.

    Thanks,
    Joe

  • http://www.blastam.com/broadcast Blast Advanced Media

    If you are using the automated tagging method, you’ll want to have your GA tag above that script tag. If you are using the manual method, it is highly recommended to move your GA tag into the head of the html. Additionally, please ensure you are using the asynchronous GA tracking script. Placing it in the top of the source code is recommended for the async version.

    Thanks,
    Joe

  • Jason

    Hi Joe, I think this is exactly what my client needs!  I have a “silly” question:  I see how you’re capturing the metrics but how do I see the results and show the client the results, e.g. number of times files were downloaded.  Thanks!

  • http://www.blastam.com/broadcast Blast Advanced Media

    Hi Jason,

    Great; glad we could help you out!

    In the GA v5 (new version), you’ll want to go to Reports > Content > Events > Top Events. You’ll see your event category listed there and you drill down into the action and label to view the number of events recorded for that file.

    Thanks,
    Joe

  • Christian Stauffer

    Quick question, does this tracking code handle context-menu downloads?

    Thanks,

    Christian

  • http://www.blastam.com/broadcast Blast Advanced Media

    Hi Christian,

    No it does not handle context-menu clicks. It could certainly be extended to do so though.

    Thanks,
    Joe

  • Nicole Slaughter

    Thanks so much for this; so glad I was directed to this solution!  I have a question as well: I did not see in the js code anywhere to put the UA for the site?  If this is the case, how will it show up in your report?

    Also, you mentioned that if you already have “multiple tracking objects” on a page then you will have to customize this code…will you have to customize if all you have is GA?

    Thank you!

  • Nicole Slaughter

    Hi again – why is there a syntax error for this code?

  • http://twitter.com/Milo_Z Kevin Robbins

    opened it in Dreamweaver and it noted a syntax error as well. on line 38.

  • Nicole Slaughter

    Yes, exactly.

  • http://www.blastam.com/broadcast Blast Advanced Media

    Hi Nicole & Kevin,

    You may be receiving a syntax error if you are not using jQuery on your site.

    Regarding your question about where to place the UA-#. This script is in addition to your existing GA tagging. Multiple tracking objects refers to multiple UA-#’s in your code, which is not common.

    Let me know if that helps!

    Thanks,.
    Joe

  • chilly53

    I am relatively new to GA and have just implemented the automated code on my site.  Where should these results be showing up?

  • http://www.blastam.com Joe Christopher

    Hello,

    After you integrate this new code, you should start to see data under Event Tracking in the interface. In the new v5 interface (click on ‘New Version’ at the top right), click on My Site > Reports > Content > Events > Top Events and you should see an event category of ‘External’ that you can drill into.

    Keep in mind that there is a delay of several hours before you’ll see this data in GA.

    Hope that helps!
    Joe

  • Sanjeev Thakur

    Hi all,

    M facing a problem while using “Tracking PDF Download (in current window)”
    working at the asp.net application,actually my anchor tag is a server side control,  soi have called this method at onclientClick :
    onclientClick=”var that=this;_gaq.push(['_trackEvent,'Download','PDF',this.href]);setTimeout(function(){location.href=that.href;},200);return false;”

    but unfortunately it is showing wrong counts in the GA?
    Any one have idea what i’m missing?

    Thanks in advance,
    Sanjeev

  • http://www.blastam.com Joe Christopher

    Hi Sanjeev,

    As long as the href is valid on your rendered server-side control, it should be tracking correctly.  You can also substitute this.href for the actual value (and put it inside single quotes).

    Once this is in place, you can see the data under Event Tracking in GA.  Please provide more information about ‘wrong counts’ and also a link to your site and I can investigate further.

    Thanks,
    Joe

  • Richard Silk

    The new window example I think is missing a closing quote from the following example: should there be a close quote after _trackEvent ?

  • http://www.blastam.com Joe Christopher

    Thanks for catching that!  Post has been updated.

  • Vickster

    I think there’s a missing bracket somewhere as I’m getting the following error on Firebug when I paste the code as entered above:

    missing } in XML expression
    });

    The line it’s pointing to is the last }); on the third line from the bottom 

  • http://www.blastam.com Joe Christopher

    Hi Vickster,

    I tested the code and it is working for me on a new page that I added it on.  Can you post a link to the site you are using it on or email me direct joe [at] [blastam].com and I’ll take a look?

    Thanks,
    Joe

  • Adendum

    There seems to have been several changes to the original code now. Is there an example of the current/final version we can see?

  • http://www.blastam.com Joe Christopher

    Hello,

    The code is up-to-date in the post. Most users have experienced issues because they were not using/referencing jQuery above the script.

    Thanks,
    Joe

  • linda

    Hi Joe!

    Thank you so much for this useful post. I’ve been looking for a solution for long.  I’m going to give your code a try but I’m not familiar with jQuery. How do I reference jQuery above the script?

    Can I simply reference it in my html and have the script in its own separate .js file? Where can I place the referencing line of code?

    Thank you kindly,

  • http://www.blastam.com Joe Christopher

    Thanks for reading our blog Linda; glad you enjoyed this post!

    You can place the code I’ve provided in its own .js file. Above this line, add a script tag for jQuery, which you can either use Google’s CDN or host it on your own server. Get it at jquery.com.

    Thanks,
    Joe

  • Jonas

    Hi Joe
    I’ve integratet jquery and your script in my website an can now see some “unique events” since the integration. But where can i see the tracked downloads in GA? Where is this category “External”?
    In “Top Events” i can’t see some categories.
    How can i see the downloads?

  • m038

    Thanks for this great piece of code. Makes the stats a lot better to read and is simple enough to modify to your own needs.

  • http://www.blastam.com Joe Christopher

    Hi Jonas,

    In the new interface version of GA, go to Standard Reporting > Content > Events > Top Events. If you have more than 10 event categories being tracked, you may have to paginate to view them all. You can also filter the report for ‘External’. External shows the external site clicks. ‘Download’ as an event category shows the downloads.

    If you still don’t see the data, send the link to your site and I can take a quick look for you.

    Thanks,
    Joe

  • http://www.blastam.com Joe Christopher

    Hi Jonas,

    I looked at your site.  You are using the traditional GA tracking syntax instead of the asynchronous.  I’d recommend updating your GA tracking snippet on all pages to use the new asynchronous method.  See http://code.google.com/intl/en/apis/analytics/docs/tracking/asyncUsageGuide.html

    Alternatively, you could update the download tracking script to convert the _gaq.push()’s to pageTracker._trackEvent()’s.

    Thanks,
    Joe

  • http://www.facebook.com/aharnak AJ Harnak

    Thanks for this code, works great!  I couldn’t find the events for the documents for the longest time, so I assumed it wasn’t working.  I followed the steps you explained to Jonas to find them, and they were there.  Thanks again.

  • http://revolutionaries.ie Tom Duke

    Joe,

    Hi – just added your code to a client site and it appears to work great for the first download on a page – the event doesn’t seem to fire for subsequent downloads though on the same page (when using Firebug).   Is that the case or am I missing the stats somewhere do you think?

    Thanks
    – Tom

  • http://www.blastam.com Joe Christopher

    Hi Tom,

    I haven’t experienced that issue.  If you email me the site at joe [@] blastam.com, I can take a quick look for you.

    Thanks,
    Joe

  • http://revolutionaries.ie Tom Duke

    Thanks for checking that out Joe – and for confirming that it’s working OK.

    And a big thanks for sharing your tracking code.

    – Tom

  • Atulsharmanoida

    Thanks for simple explanation for me. Just one question.

    In the code you mentioned, what do i write in place of  “this.href”

    Download my file

  • http://www.blastam.com Joe Christopher

    Hello, I’d recommend just leaving that as this.href. In the context of the _trackEvent call, you can replace this with something more meaningful if you like, but at that point, be sure to use a single quote around the value you pass in.

    this.href is a javascript variable that grabs the href value in the ‘a’ tag.

    Hope that helps!
    Joe

  • http://twitter.com/Kmarketing Nigel Kay

    Hey Joe, This is a really helpful resource that I shared with my network

  • Robert

    Great resource. Thank you for your time and effort.

  • Robert

    Hi Joe, 

    I have the traditional tracking code installed on my site. 

    I implemented the tracking code inside the tags for the file I am trying to track, and it looks like this: 

    I am testing on the fly as I believe that the tracking is in real-time, however the events don’t seem to be coming through on my GA screen (there have been no events at all prior to this so I am expecting my first counts to come through in my testing).

    Can you see anything wrong with what I have provided above? 

    Thanks in advance. 

    Robert

  • http://www.blastam.com Joe Christopher

    Hi Robert,

    Since you are using the traditional syntax, the code will be different. I’d recommend upgrading to the asynchronous syntax. If you aren’t able to do that, it would be the following in the onclick: pageTracker._trackEvent(‘download’,’pdf’,this.href);

  • Bingyang

    Hi Joe,

    I’m wondering how I can track the download file but without extension. I use your scripts and it really works !! Thank you for you wonderful job.

  • http://www.blastam.com Joe Christopher

    Hi Bingyang,

    You could use the manual onclick approach that I describe in the article.  Another way to do this is to add a class to the ‘a’ tag and then track all ‘a’ tags that have that class.

    Thanks,
    Joe

  • Gio

    I’m not sure the onclick event works fine with a mouse right-click. have you tested it ?

  • http://www.blastam.com Joe Christopher

    It does not work with a right click. You could probably use oncontextmenu to track that…

  • http://www.churchbuzz.org Patrick Steil

    So, if I have this code installed correctly on my page and I have the Chrome GA debugger installed and turned on (I see ga “debug” output when I load up the page… then when I click on a link to a file download, if all is working correctly, I should see a GA request spit out in the ga debug output, yes?

    Thanks
    Patrick Steil
    http://www.churchbuzz.org

  • http://www.blastam.com Joe Christopher

    Hi Patrick,

    Yes, you should see it output to the debugger console. Though by default, it will flash and disappear. If you go into the debugger settings, you can change the console to preserve log upon navigation.

    Thanks,
    Joe

  • Heidios

    Great post! I was able to use the code and it has helped with automated PDF tracking. Thank you.

    I do have a question that I can’t seem to solve through other research. The PDFs on my site that are being tracked are basic anchor links but the ones I need tracked more are accessed via images (Print Image– open PDF in new window). Analytics doesn’t seem to touch those-or any other buttons on the site for that matter. Do you recommend applying event tracking to the image properties? Thank you!

  • http://www.blastam.com Joe Christopher

    Hello,

    If the href value on the ‘a’ tag surrounding the image contains .pdf, then the script should pick it up.

    If you are describing a different scenario, then you may need to adjust the script or just manually tag. A lot of times, we’ll use a CSS class for special cases and then target all of them via $(‘.className).each();

    Hope that helps!
    Joe

  • Filterjunkie

    Joe,
    Where in google analytics do I find the tracking for the download?
    Please help.

  • http://www.blastam.com Joe Christopher

    Hi,

    You’ll find this data under Standard Reporting > Content > Events > Top Events in the new v5 interface.

    Thanks,
    Joe

  • http://twitter.com/jennatollerson Jenna Tollerson

    Will this script still work with jQuery 1.4? I know it has been updated to work with 1.6, but for reasons that are not up to me I need something that works with jQuery 1.4.

  • http://www.blastam.com Joe Christopher

    This script will work fine on jQuery v1.4

  • Anonymous

    Thank you for the speedy response!

  • http://twitter.com/logicalthings Logical Things

    Hi Joe,

    I’ve implemented this code to track clicks on a site that also includes an image map (yes, I know, an image map) on a home page image.
    While all other clicks external are successfully logged, I have found no clicks recorded for the image map hrefs. Anyone else have this issue? Any work-arounds?Cheers,Art

  • http://www.blastam.com Joe Christopher

     I believe you’d have to create a custom gadget in Google Sites to house the custom javascript.

  • http://www.blastam.com Joe Christopher

    Hi Art,

    Great question.  You can modify the script to change it from: jQuery(‘a’).each(function() {
    to: jQuery(‘a,area’).each(function() {

    Hope that helps!
    Joe

  • http://www.blastam.com Joe Christopher

    Hi Chris,

    Currently the script would track this as an external link versus a file download. If you’d rather have it track as a download, you just need to move the block of code that handles the file download tracking up above the external check. Basically, it is just moving if statements around to change the processing order.

    Hope that helps!

    Joe

  • Mortaza Kamal Nourestani

    if (typeof jQuery != ‘undefined’) {

    jQuery(document).ready(function($) {

    var filetypes = /.(zip|pdf|doc*|xls*|ppt*|jpg|ashx)$/i;

    var baseHref = ”;

    if (jQuery(‘base’).attr(‘href’) != undefined) baseHref = jQuery(‘base’).attr(‘href’);

    jQuery(‘a’).each(function() {

    var href = jQuery(this).attr(‘href’);

    if (href) {

    if (href.indexOf(‘?’) != ‘-1′) {

    href = href.substring(0, href.indexOf(‘?’));

    }

    if (href.match(filetypes)) {

    jQuery(this).click(function() {

    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;

    var filePath = href;

    _gaq.push(['_trackEvent', 'Download', extension, filePath]);

    if (jQuery(this).attr(‘target’) != undefined && jQuery(this).attr(‘target’).toLowerCase() != ‘_blank’) {

    setTimeout(function() {

    location.href = baseHref + href;

    }, 200);

    return false;

    }

    });

    }

    }

    });

    });

    }

  • http://www.blastam.com Joe Christopher

    It depends on your volume of traffic. If you have a large site with a lot of traffic, it could take 24-48 hours for processing. If you have little traffic, then perhaps as quick as 4 hours. Upon the next processing window, you should start seeing event data in your reports if implemented correctly.

    Thanks,
    Joe

  • http://www.blastam.com Joe Christopher

    @6cb23c9e2b0f1dbdc6023740c85bba19:disqus The script provided does require jQuery and of course Google Analytics. If you wish to provide your URL, I can take a look.

    Thanks,
    Joe

  • G.Dutt

    Hi Joe,
    it’s proper working for PDF download tracking but my issue is how to track image view (how many visitors view particular image of my picture gallery) through track Event method.

    Thanks in advance
    G.Dutt

  • http://www.blastam.com Joe Christopher

    @913743d3af4f9bbef5a544a26ac42bd8:disqus You’ll have to hook into the javascript that is used for your picture gallery. This is easier on some than others. If you can provide details on which picture gallery you are using or a URL to your site, I can advise further.

    Thanks,
    Joe

  • G.Dutt

    @joechristopher:disqus My photo gallery url where i want to track image views : http://goo.gl/I02l5

  • http://www.blastam.com Joe Christopher

    @913743d3af4f9bbef5a544a26ac42bd8:disqus It looks like you are using the PrettyPhoto script. You’ll have to use a callback function to hook into this. Take a look at http://forums.no-margin-for-errors.com/discussion/1505/how-to-track-individual-image-views-using-google-analytics/p1

  • Craig R Morton

    Excellent, i’ve been looking all over with this.

  • Frank

    Joe,

    We have GA and had the “old” code for tracking PDFs and what not. Use to work great, clearly things changed and we failed to notice. I found your page, and changed our URL links to include your code. We have valid GA code at the page top, do we need anything else, you mention JQuery?

  • http://www.blastam.com Joe Christopher

    @7acdc8efc3a20458fe757fe9c075fa33:disqus If you wish to use the script I provided in this post, you’ll need jQuery above the script. You can get jQuery at jquery.com. That is the only requirement of the script I’ve provided.

  • Marshall

    Joe, can you tell me if this page is set up correctly to track the file “jewishtimes.pdf”: http://www.mesora.org/newhomepage/jtimespage.html

    Thanks

  • http://www.blastam.com Joe Christopher

    @ff5f021239305e5d6519a376fa018b6a:disqus Looks like there is a syntax issue on that link element. Add a space before the onclick in the link tag.

  • Todd

    Joe, question for you. What event goal types would be used for a PDF whitepaper download? This could be a category or action but my question is what value would be assigned? Would it be a numerical value or action?
    Great post and thank you in advance for your response.

  • http://www.blastam.com Joe Christopher

    @d624755966d6aefd3cd3d52c3f5d0e2b:disqus When you setup an event-based goal in GA, you can either use the value that you pass in to the event tracking code itself (the value parameter) or you can declare a specific value in the goal setup. For the actual value, you can either enter (and even adjust in the future if it changes) the approximate monetary value of a download to you or you could use a weighting system. With a weighted system, you could do something like 1-10 where 1 is the least important goal on your site and 10 is the most important goal. I hope that gives you a few ideas.

    Thanks,
    Joe

  • Sid

    Hello,

    I’ve attempted to use your tracking code on my website, but Firefox keeps throwing me an error near to the end of the script. Here is what it says:

    missing } in XML expression

    It is referring to this:

    }); <—- it doesn't like this semicolon
    }

    Any ideas? I’m afraid I’m a bit lost on this one.

    Thanks!

  • http://www.blastam.com Joe Christopher

    @Sid You’ll need to post a link to your page and then I can take a look to see what is causing the javascript syntax error.

  • http://www.blastam.com Joe Christopher

    @mornnooneve:disqus If you can post a link to your site, that will be easier to debug this issue.

  • http://www.blastam.com Joe Christopher

    @mornnooneve:disqus I looked at your site. I clicked on a PDF and it is capturing the click as an event. If you go to ‘Content > Top Events’, you should see ‘pdf’ listed as an event category to drill into.

  • http://www.facebook.com/mortaza.nourestani Mortaza Kamal Nourestani
        &lt;script type=&quot;text/javascript&quot;&gt;
            if (typeof jQuery != 'undefined') {
                jQuery(document).ready(function($) {
                    var filetypes = /.(zip|pdf|doc*|xls*|ppt*|jpg|ashx)$/i;
                    var baseHref = '';
                    if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
                    jQuery('a').each(function() {
                        var href = jQuery(this).attr('href');
                        if (href) {
                            if (href.indexOf('?') != '-1') {
                                href = href.substring(0, href.indexOf('?'));
                            }
                            if (href.match(filetypes)) {
                                jQuery(this).click(function() {
                                    var extension = String((/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined);
                                    var filePath = String(href);
                                    _gaq.push(['_trackEvent', 'Download', extension, filePath]);
                                    if (jQuery(this).attr('target') != undefined &amp;&amp; jQuery(this).attr('target').toLowerCase() != '_blank') {
                                        setTimeout(function() {
                                            location.href = baseHref + href;
                                        }, 200);
                                        return false;
                                    }
                                });
                            }
                        }
                    });
                });
            }
    &lt;/script&gt;
    
  • http://www.facebook.com/mortaza.nourestani Mortaza Kamal Nourestani

    The code above will not work due to these 2 lines

    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
    var filePath = href;

    they need to be converted to string in order to make it work:

    var extension = String((/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined);
    var filePath = String(href);

    Below is full functional code:

    if (typeof jQuery != ‘undefined’) {

    jQuery(document).ready(function($) {
    var filetypes = /.(zip|pdf|doc*|xls*|ppt*|jpg|ashx)$/i;
    var baseHref = ”;
    if (jQuery(‘base’).attr(‘href’) != undefined) baseHref = jQuery(‘base’).attr(‘href’);
    jQuery(‘a’).each(function() {
    var href = jQuery(this).attr(‘href’);
    if (href) {

    if (href.indexOf(‘?’) != ‘-1′) {
    href = href.substring(0, href.indexOf(‘?’));
    }

    if (href.match(filetypes)) {
    jQuery(this).click(function() {
    var extension = String((/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined);
    var filePath = String(href);

    _gaq.push(['_trackEvent', 'Download', extension, filePath]);
    if (jQuery(this).attr(‘target’) != undefined && jQuery(this).attr(‘target’).toLowerCase() != ‘_blank’) {
    setTimeout(function() {
    location.href = baseHref + href;
    }, 200);
    return false;
    }
    });
    }
    }
    });
    });
    }

  • http://www.formlogix.com/web-forms/create-web-forms.htm create web forms

    Now, that will be easy for me track the PDF files. It is quite easy to debug the issue and track with your information.

  • http://www.blastam.com Joe Christopher

    @Kelly Thanks for the praise on this post! You’ll want to either find a developer to help you out in customizing the code to your needs or explore engaging with us at Blast.

  • http://www.blastam.com Joe Christopher

    @franklinparrish:disqus The quotes in your code are smart quotes. Instead of ”, a ” should be used. Fix the beginning and ending quotes on the onclick and you should be set!

  • http://www.blastam.com Joe Christopher

    @7a89e117134eff94ea0b33d6d4b30f2b:disqus When I say ‘multiple tracking objects’, I am referring to if you are sending GA data to multiple accounts on the same page. This isn’t too common. Tracker objects are called by doing something like _gaq.push(['trackerName._trackPageview']); where trackerName is the name of the additional tracker object.

  • http://www.blastam.com Joe Christopher

    @0840410c432badc846c9d08045f59cae:disqus See my response to Jon below for clarification on tracker objects. Again, this isn’t a common configuration.

    Every place in my script where we do _gaq.push([...]); would need to be customized to something like:
    _gaq.push(['trackerName._trackEvent', 'Email', 'Click', mailLink]);

  • http://www.blastam.com Joe Christopher

    @facebook-1553864902:disqus You are using the traditional syntax for your GA code on your site and then using my asynchronous syntax to track the event. You need to update one or the other. I recommend that you grab the latest tracking code snippet and use that across your entire site and then it will start working.

  • http://www.blastam.com Joe Christopher

    @provalsaub:disqus It is likely an issue with single quotes needing escaping in what I’ve provided. You’ll want to work with a developer familiar with php to properly get this code integrated.

  • http://www.blastam.com Joe Christopher

    @07de5f59f4acb619c61cd7648e0ab114:disqus I see two immediate issues. 1) Move the jQuery script above your eventTracker script. 2) Remove the beginning and ending script tag in the eventTracker script file.

  • Brendan

    Thank you, Joe. I will try these two suggestions and will report back to you.

  • Brendan

    That did the trick, Joe! Thank you for your help and awesome code! Perhaps the most helpful bit of js on the net!

  • http://www.blastam.com Joe Christopher

    @07de5f59f4acb619c61cd7648e0ab114:disqus Great! I’m glad I was able to help you out.

  • Jessie

    I have this installed, but can’t see where the results get posted in google analytics – do you have any documentation on that? I am finding google analytics pretty hard to navigate…

  • Julian

    It worked, thanks alot!

  • http://www.blastam.com Joe Christopher

    @72f2a1a7557426f53595e57ad80c5b57:disqus This data will be captured under the Events reports. You can get to this by going to Standard Reporting > Content > Events > Top Events. This report will show the event category and you should see ‘Download’ for example and then you can click into that to see the event action and then click into that to see the event label.

    I hope that helps!

    Thanks,
    Joe

  • Barbara

    Is it possible to copy the code for tracking the download also in a swf file’s code?
    Thanks, Barbara

  • http://www.blastam.com Joe Christopher

    @disqus_cug0DN1pSA:disqus You will want to use the ExternalInterface.call() to send the javascript to the containing page (the script I have provided is just for html links). The ActionScript would be something like: ExternalInterface.call(“_gaq.push(['_trackEvent','Downloads','click-pdf','filename.pdf']);”);

  • DBL

    Hi Joe, thanks for the helpful post. I’ve been trying to set this up on my page http://amath.colorado.edu/student/larremore and I can’t seem to get any events to register (downloading of any PDFs on the site, e.g. my CV). At first I thought it was a smart quote issue, but I think I’ve fixed that. Do you see anything wrong in the implementation? Thanks! Dan

  • http://www.blastam.com Joe Christopher

    Hi Dan,

    I checked the code on your CV link and it is working correctly. Can you double check in GA? You should see the data in Standard Reporting > Content > Events > Top Events and then you should see an event category of ‘Download’ that you can click into and then an event action of ‘CV’. If you still don’t see it, you may have a profile filter preventing the data from showing.

    Hope that helps!
    Joe

  • DBL

    Hi Joe,
    Thanks for the confirmation. Sure enough, when I checked this morning, there are working events, though when I checked yesterday, there were not. To any other Google Analytics noobs like me who may read this in the future, don’t be surprised if there is significant latency in your Analytics…it may stil be working, and the “is this working?” testing may take a couple days to nail down. Joe, you’re the best. Thank you sir!
    Dan

  • http://www.satinderspace.com/ Satinder Singh

    Thanks for sharing this script, is it necessary to setup Goals in GA after this if yes then tell me how can we setup goals in GA to track downloads

  • http://www.blastam.com Joe Christopher

    @satinderspace:disqus You have the option to setup goals in GA after you’ve enabled tracking. If you are firing the tracking code of a download as an event, then you’ll want to configure a new goal in GA as an ‘event’ goal type. Please see our other blog post on how to add event-based goals: http://www.blastam.com/blog/index.php/2011/03/how-to-use-events-goals-google-analytics/

  • http://www.satinderspace.com/ Satinder Singh

    Thanks for solution….

  • http://twitter.com/SusannaQ2 Susanna Kirk

    Thanks for these instructions! They’re so much clearer than others I’ve found.

    I thought I fixed it, but I STILL can’t get my event tracking to function. I turns out, I finally noticed in my view page source, that my CMS automatically rearranges the order of the components in the tag, so that the code is rewritten like this:

    I don’t know what that last ?=”” is.
    Could the reordering of the code be why the event tracking isn’t working? Would that make the difference?

    Your insight would be really helpful. I’ve been trying to figure this out solo and I’ve hit a wall.

  • http://www.blastam.com Joe Christopher

    @4d39016160fbf89e4b06c8e9406bc1c7:disqus If you don’t see data there, then there is a problem with how you placed the code or your GA configuration. If you can provide a link, I’d be happy to take a look.

  • http://www.blastam.com Joe Christopher

    @e0a1faa0814104aa9575be336a4292c1:disqus I don’t think the jQuery version would impact this script. I looked at the URL you provided, but I don’t see any scripts in there nor jQuery.

  • http://www.blastam.com Joe Christopher

    @twitter-20695839:disqus It doesn’t sound like the CMS is causing this issue. Can you provide a link and I’ll check it out?

  • http://twitter.com/SusannaQ2 Susanna Kirk

    Hi Joe, I finally figured out what went wrong on the sites for which I was trying to create event tracking. They were set up with the old synchronous GA tracking code. I don’t understand this stuff well enough to know where the breakdown happens, but after I switched the sites to the new asynchronous code, the event trackers started logging the events properly. Thought I’d post an update, in case anyone arrives here wondering why they can’t get their event trackers to track. Thanks again for the great tutorial!

  • JamMasterLoveJoY

    I spent a whole day looking and then i realized after finding this that i had it already bookmarked. Thank You. Got an add I can click or something? =D

  • JamMasterLoveJoY

    I meant to say ad. hehehe =P

  • http://twitter.com/dimensionasalon Dimension A Salon

    Thanks for clearing up some areas I was not grasping. I may have a M.S. In Internet Marketing, but I’m no programmer. Heck, even being GAIQ certified is not enough. Most appreciated!

  • Sheppe Pharis

    Great post!

  • QuHarrison Terry

    Thanks

  • http://joaocorreia.pt/ João Correia

    Hello Pooledesign,

    You don’t actually need to set it up as a goal, but you can if you want to.
    The downloads will appear in the events section on GA interface.

    Thanks

  • http://joaocorreia.pt/ João Correia

    I Edric,

    I didn’t see the Google Analytics event being fired. You might want to revise the code. Start by placing the code inline and go from there.

    Download my file

    Thanks

  • http://joaocorreia.pt/ João Correia

    Hello Edric,

    You have double quotes on your onlick.

    onclick=””_gaq.push(['_trackEvent','Download','PDF',this.href]);””

    If you remove them it’s actually working. You should add the timeout as explained in the article.

    onclick=”_gaq.push(['_trackEvent','Download','PDF',this.href]);”

    Thanks

  • Jason

    This thing working???

  • http://www.facebook.com/jessevanhiller Jesse Van Hiller

    Thanks Joe!

    I have a simple download j needed to track and copied the first example into my code. It didn’t work at first but then I kept reading and saw that the quotes were pasted as special characters in my code.

    I just replaced those with regular quotes and I saw stats immediately.

    NOTE FOR BEGINNERS AND NON CODERS: make sure you replace the quotes once you paste code.

  • http://joaocorreia.pt/ João Correia

    Hi Jason,

    Yes it will work for every href where you add the onclick event, even if its on another server and has a roll-over.

    Thanks
    Joao

  • http://www.facebook.com/bolla.pinnsvin Karine Haug

    Thank you for sharing :)

    I’ve got one problem though. I’m using the “current window” script, and in ie7/8 this forces a security bar at top of the window saying “To help protect your security, Internet Explorer blocked this site from downloading files to your computer”.

    Any way to get around this?

  • http://twitter.com/morfje HClement

    Thank you so much for this script! It works fine in my site for tracking mailto’s and outgoing links. It also tracks downloads but the urls to the download are doubled (which result in 404 errors). Is that a known issue?

    I cannot post my site url here as it is the test-site with a login. Hope to hear from you. Bye!

  • Jessie Johnson

    This seems to be the only script of its kind, so I’m keen on getting it to work, but for some reason it’s not. Any suggestions?

    http://centeronschoolturnaround.org/test/

  • Jessie Johnson
  • http://joaocorreia.pt/ João Correia

    Hi Jessie,

    I looked at your page and the event is firing. Can you check you events under Analytics. What are you using to debug the event firing ?

  • Jessie Johnson

    Are you looking at http://centeronschoolturnaround.org/test.htm If you view source there’s no event data being added to the a href.

  • http://joaocorreia.pt/ João Correia

    Yes, definitely! You can use jQuery to extract the documentid and send that information to the event.

    Joao

  • http://joaocorreia.pt/ João Correia

    Hi Jessie,

    Thats correct, you wont see it in the HTML.
    jQuery .click() binds the “click” event and executes the trackEvent on “click”.
    You can see the events being fired by using httpfox or Charles http proxy.
    Either way check your analytics, the events should be there.

  • Jessie Johnson

    I installed httpfox, but I’m not sure what I’m looking for once it’s on and I’ve clicked a link. I have zero experience with this.

  • Jessie Johnson

    I added an actual file to be downloaded for the first sample, then turned httpfox on but I just see a couple errors.

  • http://twitter.com/dustin2k Dustin Graham

    Hi Joe, looks like a little logic bug in the code.

    Line 14 and 31 I think you mean to do:

    if (!jQuery(this).attr(‘target’) || jQuery(this).attr(‘target’).toLowerCase() != ‘_blank’) {

    The current code as written doesn’t work as intended. I suspect the intention is to do a setTimeout if target is not _blank. However, as written, if target is undefined, it doesn’t use setTimeout.

  • kex301

    Maybe you should check if the quotation mark is proper. It should be ” not ”

  • MilesK

    Just a formality: do you hereby grant anybody a license to copy and use the above automation script in any way they see fit? As it stands, the site has a copyright which covers everything on it, so we’re not technically able to copy the code. Ideally, you could put the license as a comment right in the code.

  • http://www.multiplyleadership.com Mark Jones Jr.

    Thanks!!

  • http://www.blastam.com Joe Christopher

    @disqus_Ydofl4HjGc:disqus We publish this code with the intent that people will use it as they see fit. We will look into a license comment to add to the code.

  • Anne

    Hi Joe thanks for sharing the script! Our web developers have implemented the code on our acceptance server and it works fine for two of our websites, but nothing happens on the one that’s behind an https reverse proxy. Could that be a problem? Hope you can help, despite the fact that you posted the script two years ago!

  • http://profiles.google.com/drtimoneill Tim Oneill

    Yeah, but that is only if they start the download … isn’t it?

    What if it is (say) a 200Mb file and they start but don’t finish the download. How can we get stats for COMPLETED file downloads?

  • http://www.blastam.com Joe Christopher

    @google-b761de35e28950984301befc0e8fa941:disqus Yes, you are absolutely correct that this is tracking intent of a download. There is no way to track download completes in GA since we aren’t referencing server logs.

    Now, with enough hacking, you could probably do this and issue an unsupported server-side GA hit from a process that reads your web server log files and rebuilds the cookies, etc to issue a GA hit. Intent I find is usually pretty good in relation to all of the effort required to do something like this. Universal Analytics by GA (currently in limited beta) makes this sort of thing a little bit easier.

  • http://www.blastam.com Joe Christopher

    @disqus_4rr8Zlg2FT:disqus Sure; either post your URLs here OR email it over to me. Email is joe at blastam

  • http://www.blastam.com Joe Christopher

    We just updated the technique used for download and external link tracking in our latest blog post. Check it out: http://www.blastam.com/blog/index.php/2013/03/how-to-track-downloads-in-google-analytics-v2/

  • Doru Catana

    how soon will the event tracking refresh? (see actual data)

  • http://www.blastam.com Joe Christopher

    @dorucatana:disqus Event data is processed generally between 4-24 hours. In some cases, it can be quicker and in other cases longer (even around 48 hours for very high volume, non GA Premium sites). It depends on your site’s volume.

  • john bracey

    You spoke about an automatic tag generation app Analytics Engine. Are there apps like this that can generate tags across multiple analytic platforms that you know of? We often run multiple analytic platforms simulationiously.

  • http://www.blastam.com Joe Christopher

    @johnbracey:disqus Not specifically, but check out this solution, along the same idea: https://segment.io/libraries/analytics.js

  • john bracey

    Glanced over it and it sees like that would certainly be a solution. Do you know if the solution works for Omniture and/or web trends for example? (I want to make sure it doesn’t only apply to open source Analytic tools)

  • http://www.blastam.com Joe Christopher

    I don’t believe they have support for either of those tools. Your other option is to build javascript wrapper functions. I’ve done this in the past and it worked out well.

  • Charles Guo

    Thanks for sharing! Great article!

  • http://www.facebook.com/ernie.natera Ernie Natera

    Thanks for making it so easy. Can you review mine? I entered it on some pdf links to test, but nothing is being recorded in GA.
    http://svswa.org/board_of_directors.cfm

  • http://www.blastam.com Joe Christopher

    @twitter-632430750:disqus thanks for sharing. Pretty cool service.

  • http://www.facebook.com/kristin.dean.50 Kristin Dean

    This is hands down the most helpful post I have found on this topic. Setting the delay made all the difference in my events showing up in GA. Thank you!

  • Thom

    Hi, thanks for this. Very helpful.

    Is there any way to track downloads that don’t occur as a result of someone clicking on the link on my website? For example, if another website includes the direct URL for a PDF on my site, then vistors won’t ever click on the link on my site and presumably GA won’t count this?

    Any help greatly appreciated.

  • http://www.ysugarcrm.com/ sugarcrm development

    I putted inline download code for a PDF eBook on my website but the problem is there, I haven’t seen anything in Google Analytics events, real time or etc. Is there any other code on my page that is preventing
    tracking code from working?

  • Sukhrob

    Joe, i was able to make it work, thank you! One question: where in GA can I find the history of all downloads? Thanks – Sukhrob

  • Sukhrob

    Behavior -> Events -> Pages -> downloads -> pdfs

  • Sukhrob

    Joe, does it work with jQuery mobile?

  • disqus_NyXcRA1Xq8

    Hi, I tagged a pdf and mp3 link on my site but nothing is showing up in Google Analytics. Could you take a look?

  • http://javaglory.com yari

    thank for you to share this article ,it’s lot help me .



Goal Driven Online Marketing & Analytics
Copyright © 1999-2013 Blast Analytics & Marketing