Google Analytics

Outgoing Link Tracking With Google Analytics

Learn how to track outgoing links using Google Analytics & jQuery.

By default Google Analytics will track the exit page, or last page a user views while on a website. What it won't track is what link that user clicked to leave the site. With a little jQuery this can become a reality.

The Old, & Wrong Way

I've seen it time and time again, developers using the pageTracker._trackPageview function to track things that aren't pages. While pageTracker._trackPageview will do the job it creates false page views and inflates reports.

I would argue that a user clicking a link to leave a website is really a page view on the external site, not the developer's site. Below is the old method to achieve this:

<a href="http://www.nealgrosskopf.com/" onclick="pageTracker._trackPageview('http://www.nealgrosskopf.com/');">Outgoing Link</a>

The Right & New Way

Google Analytics has a new method of tracking all things that aren't page views. This new technique uses the pageTracker._trackEvent method.

First import Google's hosted jQuery library:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>

Next, within the $(document).ready function which is triggered when a page is finished loading, use the following Javascript:

<script type="text/javascript"> $(document).ready(function(){ $("a[href^='http://']").click(function(){ pageTracker._trackEvent("links", "external", $(this).attr("href"), 0); }); }); </script>

This will target all link hrefs starting with "http" and add an onclick event handler to them.

Dissecting pageTracker._trackEvent

The following is taken directly from Google's guide to pageTracker._trackEvent

  • Category (required) - The name you supply for the group of objects you want to track.
  • Action (required) - A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object.
  • Label (optional) - An optional string to provide additional dimensions to the event data.
  • Value (optional) - An integer that you can use to provide numerical data about the user event.

And again, as it would appear in Javascript

pageTracker._trackEvent("Category", "Action", "Label"), Value);

While Google specifies what each of the variable placeholders should be they can certainly be named whatever you want. Action does not need to be a verb (as you can see in my original example). Feel free to use each of the placeholders however you see fit. One thing to note is the last variable (Value) must be an integer.

How the Data Looks in Google Analytics

Below is how the report will look in Google Analytics once some data is collected. This data can be sliced and diced using Advanced Segments just like any other dimension in Google Analytics.

How The Data Looks in Google Analytics

Further Reading