Tracking users downloading your files can be a great way to tell if users are using your site as you intended. As an example, If you have a business site that hosts PDF files and zip files for customers to download you probably want to know if, and how many times these documents are being downloaded to gain a better understanding on how successful your site’s flow is.
The official Google Analytics developer documentation says that you can fire a page view event manually like below:
However, adding an onclick event to every download link in your website in some instances could be downright painful.
jQuery + Mindless tasks = Happy Ninja
doc, docx, eps, xls, xlsx, jpg, png, svg, pdf, zip, txt, ppt, vsd, vxd, js, css, rar, exe, wma, mov, avi, wmv, mp3
Now the list above could be longer, it might want to include something special for your implementation, I’ll leave the addition of new file types up to you.
Lets make it happen
So your first step before continuing should be to mosey on over to the jQuery site and download the latest version. Once downloaded link to it in between your <head> tags like so:
What we want is a simple bit of code that detects all the links on a page and checks to see if:
- It is a local link to something on your site
- It is to a file type that matches our list above
Wrap that up in some anonymous methods and we have the following:
Now you’ll notice that the above has been modified to only include a short list of files. I did this simply to make sure they would all fit on the page properly, and you should have no problem adding more using the same format or |extension|.