How to track multiple links from page A to B in Google Analytics

I'm pretty sure a lot of you have dealt with this issue in the past. Someone puts a link on a specific page and after a while they ask you how many clicks it got. But in the main menu and footer are links to the same page also... Google Analytics can only report on how many people went from page A to B, but not which specific link they used.

Take a look at this blogpost:

It has 4 links to the same page, and there's no way to differentiate them in Google Analytics, until today 🙂 I wrote a script that detects on all pages if there are multiple links with the same destination. The script looks like this:

function stripHash(url) {
if (url.indexOf("#") > -1) { url = url.substr(0, url.indexOf("#")); }
return url;
};

function getPath(url) {
if (url.indexOf(document.domain) > -1) {
url = url.substr(url.indexOf(document.domain) + document.domain.length);
if (url == "") { url = "/"; }
}
return url;
};

function tagDuplicates(arr) {
var obj = [];
for (var i = 0; i < arr.length; i++)
{
var page = stripHash(arr[i].href);
if (obj[page]) {
obj[page]['count'] += 1;
arr[i].setAttribute("ga_clickindex", obj[page]['count']);
obj[page]['first'].setAttribute("ga_clickindex", 1);
} else {
obj[page] = new Array();
obj[page]['count'] = 1;
obj[page]['first'] = arr[i];
}
}
};

jQuery(document).ready(function () {
tagDuplicates(document.getElementsByTagName("a"));
jQuery('a[ga_clickindex]').mousedown(function(e) {
_gaq.push(['_trackEvent', 'doublelink', 'from ' + location.pathname, 'link ' + jQuery(this).attr('ga_clickindex') + ' to ' + getPath(jQuery(this).attr('href')),,true]);
});
});

If you put this on your site you will get this report (in "Top Events" and in the table click on "doubelink"):

And if you click on the "from /" (which means from the homepage) you will see this:

The "link 4" means that people used the fourth link in the DOM to get to this page. If you look at the first mentioned screenshot you can see link 3 is not used by anyone in the last month.

Caveats/remarks

It could happen that suddenly an extra link was added to the same page, in that case the numbers won't work anymore. But for a reasonable static site this solution works perfect.
As you can see the hash (#) is also tracked with this script, so if you want a more reliable way of differentiating between links you could add hashes to them.
The best way to find out which link has which number you can view the source of a page, press on ctrl-f and search for the URL you want to see the clicks on:

Happy analyzing!

Click to activate social bookmarks