Welcome to Part 3 of Tracking Clicks with Google Analytics! Last time I discussed the process and theory behind tracking visitor click data in GA. This technique is primarily used to track non-HTML files and outbound links. In this post we’ll discuss a quicker, easier way to implement the click tracking. Please make sure you’ve read Part 2 before reading this post.
You’re probably wondering how this all woks. I’m not going to get into the nuts and bolts, but this uses the DOM or Document Object Model. Using the DOM in the code gives us the ability to modify the HTML in real time.
About the Script
This script will only track clicks on anchor tags. It will not track clicks on images or other HTML elements.
If the anchor tag points to a different domain then
urchinTracker() is executed before the visitor leaves the site and a pageview named ‘/outbound/<url>’ is created in Google Analytics. The <url> part is replaced with the value from the HREF attribute in the anchor tag.
If the anchor tag points to a non-HTML file then the scrip creates a pageview named ‘<path>’ where <path> is the value in the HREF attribute of the link.
Here’s an example of the script in action. The link below will take you to a test page where you can click on links to other domains and files Rather than send the data to GA, the script has been modified to display a message (note: a new window or tab will open in you browser).
And here is the source code for the above page:
Installing the Script
Installing this script is simple. Copy and paste the code from the test page and place it in your web page. I place it before the closing BODY tag. After the script has been installed you can configure it to work with your site. Also, make sure that the Google Analytics tracking code is installed on the page.
Customizing the Script
There are a few customizations you can make to the code.
First, there is a variable named debug. When it is set to 1 the script will display a pop up window when a link is clicked. Set debug to 0 to disable the pop up. By default, debug is set to 1 (on).
Next, you can define the types of non-HTML files that this script will track. Find the variable named fileTypes. The value should look like this:
To track additional file types just add the extension to the list. Make sure you match the text-formatting of the existing list.
Finally, you can change the way external links appear in the GA reports. By default, all external links will be preceded by ‘/outbound/’. If you would like them to appear differently change the
There are lots of scripts like this. This is just our version. I hope it gives you some idea of what is possible and inspires you to create one of your own or modify ours. Just remember that this script will create additional data in your GA profiles. You many need to add a filter to deal with the extra data.
Please feel free to use and modify this script. The only thing we ask is you share the changes with others.
Like this post? Share it: