Track outgoing links using jQuery and Google Analytics

6 Nov 2012

Site owners using Google Analytics might know about Event Tracking, a feature with a lot of potential. This blog is about using jQuery to set up the tracking of outgoing links (or outbound links). The content is meant for sites using the asynchronous Analytics. Not sure if you're using it? Check the source code of your webpage for the following string:

	g.async=true;

If it's there, you're using the asynchronous version of Google Analytics.

Google provides Javascript function for tracking events. This function should be called every time an outbound link is clicked by the visitor. 

	_gaq.push(['_trackEvent', 'Outbound clicks' ,'http link']);

Instead of adding this script to every link in your webpage you might consider using the jQuery framework. The following jQuery selector gives you all the outbound links on your webpage:

	$('a[href*="http://"]')

Explanation:

Now you have selected all outbound links and need to tell Google which links are clicked. This is done by the following snippet of Javascript:

	var link = $(this).attr('href');

Explanation:

  1. The $ sign is the default selector for HTML elements on your webpage (DOM elements).
  2. The a is the anchor tag used in your webpage for HTML links.
  3. Between the square brackets you see the attribute selector for selecting the href, used to specify the location to which the link is pointing.
  4. The *= validated the location for containing http://

This provides a new variable containing the location of each outbound link. You should take the above input to a Javascript function like the following example:

	function trackClickOut() {
		$('a[href*="http://"]').click(function(){
			var link = $(this).attr('href');
			_gaq.push(['_trackEvent', 'Outbound clicks' ,link]);
		});
	}

Now all you have to do is call the trackClickOut() function each time a webpage is loaded. 

Why should you do this?

From now on you know which outbound links are used by your visitors. You should research this data because of the following reasons:

  1. It tells you which links are obsolete and can be removed from your webpage. Less outbound links means more link juice for other links.
  2. It tells you which links are popular. You might contact the website and ask for a backlink to your website, which might help you push up your pagerank.