Easily track outgoing links with jQuery and Google Analytics
Posted: May 19th, 2011 | Author: bart | Filed under: Javascript, JQuery, SEO, Web Development | Tags: google analytics, statistics | 1 Comment »Outgoing links on your websites cause 3 things:
- Take linkjuice away from your page
- Drive traffic away from your webiste
- They don’t allow you to measure the amount of clicks on that link
The first problem, you have to sort manually by adding the rel=”nofollow” attribute to all external links, as recommended by Google.
The second and third problem, can be easily fixed by using jQuery. I’ll show you how:
Opening external links in a new tab
By opening those links in a new tab, your page stays open, therefore not driving the user away from your page.
Normally, this is done by manually appending target=”_blank” to each link. Let’s let jQuery do that for us.
$(document).ready(function(){ $("a[@href^='http']").attr('target','_blank'); });
(Do note that I chose to define links starting with ‘http’ as external links)
Tracking clicks on external Links
We can track links by using Google Analytics Event tracking:
$(document).ready(function(){ $("a[@href^='http']").click(function(){ _gaq.push(['_trackEvent', 'External Link','Click', $(this).attr("href")]); }); });
Putting it all together
$(document).ready(function(){ $("a[@href^='http']") .attr('target','_blank') .click(function(){ _gaq.push(['_trackEvent', 'External Link','Click', $(this).attr("href")]); }); });
Help! My internal links also start with ‘http’
No problem, you can do like me and borrow this trick from Karl Swedberg:
$('a').filter(function() { return this.hostname && this.hostname !== location.hostname; }) .attr('target','_blank') .click(function(){ _gaq.push(['_trackEvent', 'External Link','Click', $(this).attr("href")]); });
