Use jQuery with Google Analytics to Track Clicks on Outgoing Links From Your Site.

1. Download jQuery and install Goolge Analytics.

Go to jQuery.com and get the latest version. Then add the script include into the header of your site.

<script type="text/javascript" src="jquery-1.2.6.js"></script>

Now go to Google Analytics. Set up an account and follow the directions to get tracking running. Go ahead, do it now, I’ll wait. You should now have some script on your site that looks like:

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js'
type='text/javascript'%3E%3C/script%3E"));
 
var pageTracker = _gat._getTracker("YOUR ACCOUNT NUMBER HERE"); pageTracker._trackPageview();

2. Add the jQuery to start tracking links.

In the head section of your page, you will need to add a few lines of JavaScript. You will need to setup the jQuery .ready function and add the code to that.

$(document).ready(function(){
 
});

Next use a jQuery selector to select all a tags on the page with a rel=”external”. To do this, pass jQuery the a tag element with the attribute selector option.

$("a[rel*='external']")

with this we add a click function to our jQuery object.

$("a[rel*='external']").click(function(){
 
});

With the last part we put in the function call to the Google Analytics code and we pass it the href that our a tag is pointing to.

pageTracker._trackPageview('/outgoing/'+ $(this).attr('href'));

This code makes the call to Google Analytics and passes a page path of “/outgoing/” and the url of where the click was headed. In your Google Analytics under content, you will see pages that start with “/outgoing/”. These are clicks that took people off your site. See below for how it looks in Google Analytics.

76 Responses to Use jQuery with Google Analytics to Track Clicks on Outgoing Links From Your Site.

  1. Great tip, I’m going to implement this on my site asap.

  2. Pingback: Tracking outgoing links with jQuery and Google Analytics, in webtoolkit4.me

  3. Pingback: Websites You Shouldn´’t Have Missed in August

  4. Pingback: S A N D E E P [ I N D I A N I C ] » Blog Archive » Websites You Shouldn’t Have Missed in August 2008

  5. Nice!

    Clean code and nice solution!

    Thanks, David Carreira

  6. Pingback: rss blog » Blog Archive » Websites You Shouldn’t Have Missed in August 2008

  7. Pingback: Websites You Shouldn’t Have Missed in August 2008

  8. Pingback: Websites You Shouldn’t Have Missed in August 2008 | POLPDESIGN

  9. Pingback: Technology Story» Blog Archive » Website You Shouldn’t Have Missed

  10. That sounds excellent!

    Will go try it now.

    How do we do similar thing with clicks on email links?

    Thankyou

    Sarah

  11. Pingback: Outgoing Links Track Feature Enhancement on Google Analytics with jQuery « Analytics, Google, jQuery, Content, Overview, Note, URLs, Panel « Sharebrain

  12. Pingback: » links for 2008-09-01 | Paul Cowles

  13. Doesn’t this technique screw up your pageviews figures, though? Any page ‘hit’ recorded with _trackPageview() will add 1 to your pageview figures, so someone arriving on a page and then clicking an external link will record 2 pageviews.

    You could search for all outgoing links and deduct that from the total, but it’s still something that could trip some people up.

  14. @Matthew

    Thanks for pointing that out. You are right it may add to the hit count I will test this on my site and see what it does. But it is the way Google recommends tracking outgoing links. You can see more info here.

    http://www.google.com/support/googleanalytics/bin/answer.py?answer=55527&topic=11006

  15. Ryan Lange

    I’m somewhat of a jQuery newbie, but shouldn’t this…

    > $(a["rel*='external'"])

    …actually be this…

    > $( ‘a[rel*="external"]‘ )

    …? (note the placement of the single and double quotes)

  16. @Ryan

    Thanks for catching the typo i updated the article to be correct. Thanks again.

  17. Thanks for good ideas and inspiration !!

  18. I’m working for the Red Cross and we basically hve to different kinds of outgoing links. “Real” outgoing links go to another domain but also a lot of links that go directly to PDF documents that are hosted on our servers but which cannot be tracked with GA. Unfortunately I’m not fluent in Javascript – but am I right to assume that your script would not be able to show us people who “exit” to PDFs?

  19. @Go-Gulf
    The script should show those that also exit to a PDF as long as the link was marked as external. If it is not you would have to modify the script to look for links that went to PDF’s.

  20. Hi there,

    I can’t seem to get this to work. Maybe I understood it incorrectly.

    Is all I need to do insert the following into my header?

    $(“a[rel*='external']“).click(function(){
    pageTracker._trackPageview(‘/outgoing/’+ $(this).attr(‘href’));
    });

    Or am I missung something??

    Thanks

  21. Hi Victoria,

    Did you include jQuery? The code needs to be placed inside of jQuery’s $(document).ready function. If you can send a link to the file I will take a look at it.

  22. Hi Josh,

    I emailed it to the gmail account advised on Joshlyford.com

    Thank you in advance. Your help is much appreciated. :-)

  23. You don’t need to add a rel attribute to the link tag just to get tracking like this. If all you’re wanting is to get all links going to external sites/sources, just use this code:

    $(‘a[href^="http"]‘)

    if your site is set up correctly you’re using relative or absolute pathing for your internal links. This leaves only true external links using http in the href attribute.

    This way you, or your content editors, don’t have to remember to add the extra item to your outgoing links.

  24. thx, really helpfull

  25. Pingback: Recent Faves Tagged With "jquery" : MyNetFaves

  26. Pingback: Ultimate Collection of 40+ jQuery Tutorials and Resources | The Theme Blog

  27. Pingback: Booto’Design » Blog Archive » 40+ jQuery Tutorials and Resources

  28. Pingback: Usare jQuery e Google Analytics per Tracciare Clicks in uscita dal tuo sito web | sastgroup.com

  29. Pingback: Usare jquery e google analytics per tracciare clicks in uscita dal tuo sito web

  30. Pingback: 40+ Excellent jQuery Tutorials | instantShift

  31. Jquery only works if your pages are HTML compliant.

    If your pages are HTML incompliant, you have to do this manually with the DOM functions in javascript.

  32. Very good solution…. and clean code…. thanks a lot

  33. Pingback: 86 jQuery Resources To Spice Up Your Website | Hi, I'm Grace Smith

  34. Hey, it is quite complicated, but it is really worth the hassle. I took me 2 hrs until I had it run. special Thanks to eddy matthews, whos remark helped me to find my mistake. I used absolute paths for my internal linking, but thar didn’t work.
    Again: great tool, it is woth the time you spent with it
    Zauberer Jan Ditgen
    Germany

  35. Thank you. A very helpful tool!

  36. Victor

    has the issue of double counting pageviews being addressed in the current code?

    could you post the full code from start to finish? ( some of us who dont know any code at all will find it hard to piece it all together.) thank for a great solution.

  37. You can use the following jQuery selector to find all offsite links on a page, e.g. to track clicks or add a CSS class:

    $(‘a[href^=http]:not(“[href*=://' + document.domain + ']“)’);

  38. I’m really not sure how helpful this is. It’s a neat trick, but as far as tracking the links people click on to leave your site… why?

  39. Thanks for that!
    I use the following:
    $(document).ready(function() {
    $(‘a[href^=http]:not(“[href*=://' + document.domain + ']“)’).click(function() {
    pageTracker._trackPageview(‘/out/’+$(this).attr(“href”));
    });
    });

    cheers

  40. I like the tool, it really helps heaps.

    Thank you and greets

    Florian

  41. I use the following:
    $(document).ready(function() {
    $(’a[href^=http]:not(”[href*=://' + document.domain + ']“)’).click(function() {
    pageTracker._trackPageview(’/out/’+$(this).attr(”href”));
    });
    });

    worked for me!!

    Seiko Ananta

  42. _trackPageview does what it says – tracks a page view. For tracking external links _trackEvent would be a much better way to do things.

    http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html

  43. Hi,

    I am not a programmer and instructions are not clear to me. Point 1 seems to be clear, but point 2 is not. For examle, ‘Next use a jQuery selector’. What is jQuery selector? Where do I find it?

    I am looking for simple solution to track my outbound links.

    Please, help.

    Regards,
    Oleg

  44. I’m using jquery.gatracker.js so I had to use:
    $.pageTracker._trackPageview(‘/outgoing/’+ $(this).attr(‘href’));

  45. How soon will you update your blog? I’m interested in reading some more information on this issue.

  46. GOOD Code!

    Thanks for sharing man.

  47. Pingback: 50 Useful New jQuery Techniques | Developer's Toolbox | Smashing Magazine

  48. Pingback: 50 Useful New jQuery Techniques

  49. We are currently using the event tracking function of GA to do this like mentioned in the comments above. We also track downloads and mailto’s. We use the following code:

    	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
     
     
    	try {
    					var pageTracker = _gat._getTracker("UA-code-hete");
    			pageTracker._initData();
    			pageTracker._trackPageview();
     
    		$('a').click(function() {
    		  var $a = $(this);
    		  var href = $a.attr('href');
     
    		  if ( (href.match(/^http/i)) &amp;&amp; (! href.match(document.domain)) ) {
    		    var category = 'outgoing';
    		    var event = 'click';
    		    var label = href;
    		    pageTracker._trackEvent(category, event, href);
    		  } else {
    		  	if ( href.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/i) ) {
    			    var category = 'download';
    			    var event = 'click';
    			    var label = href;
    			    pageTracker._trackEvent(category, event, href);
    		  	} else {
    		  		if ( href.match(/^mailto:/i) ) {
    			    	var category = 'mailto';
    			    	var event = 'click';
    			    	var label = href;
    			    	pageTracker._trackEvent(category, event, href);
    		  		}
    		  	}
    		  }
    		});
    	} catch(err) {}
    • Thanks @Roderik

      @Josh, you could alter your tutorial/tip to use _trackEvent which would fix the issue with false pageview count.

  50. Pingback: 50 Useful New jQuery Techniques and Tutorials « Tech7.Net

  51. Pingback: 50 Useful New jQuery Techniques and Tutorials

  52. Pingback: Wordpress Blog Services - 50 Useful New jQuery Techniques and Tutorials

  53. Pingback: AMB Album » 50 Useful New jQuery Techniques and Tutorials

  54. Pingback: 50 Useful New jQuery Techniques and Tutorials - Programming Blog

  55. Pingback: 100 jQuery Samples | Resources

  56. Pingback: 100 jQuery live samples | CSS Experiments

  57. Pingback: 50 Useful New jQuery Techniques and Tutorials | huibit05.com

  58. Pingback: 50 Useful New jQuery Techniques and Tutorials « Kata learns to code

  59. Pingback: 50 Useful New jQuery Techniques and Tutorials « William Rodriguez Portfolio

  60. Pingback: 8 Tips for Tracking With Google

  61. Great article! Thanks for taking the time to explain Use jQuery with Google Analytics to Track Clicks on Outgoing Links From Your Site. I’ve been thinking about similar topics lately, and it’s good to see that I’m not alone. What do you think about Customizing HTML forms with jQuery?

  62. Pingback: 50 Useful New jQuery Techniques and Tutorials | MisrIT Reader (Beta)

  63. Pingback: Twitter Trackbacks for Use jQuery with Google Analytics to Track Clicks on Outgoing Links From Your Site. | Think2Loud [think2loud.com] on Topsy.com

  64. Pingback: Script jQuery h?u d?ng « “Ngoc Design”

  65. Pingback: 50 Useful New jQuery Techniques and Tutorials « Why Limit Media

  66. Pingback: 50 Useful jQuery Techniques « Daily Apps|Useful Online Resources Collection

  67. Thanks for this peace of code. It helps a lot.

  68. Pingback: Advertisers Blog » Blog Archive » 50 Useful New jQuery Techniques and Tutorials

  69. Pingback: 50 Useful New jQuery Techniques and Tutorials | Search Engine Optimisation

  70. Pingback: 25 Essential Google Analytics Resources

  71. Pingback: 25 Essential Google Analytics Resources | TwitTrix

  72. Pingback: 50 jQuery Techniques And Tutorials | oOrch Blog

  73. Pingback: 78 jQuery Scenarios to Fall in Love | ProgrammerFish - Everything that's programmed!

  74. A verry helpfull tool. Thank you. This toll ist perfekt for my Photographs Webseite in Germany. Regards from Cologne,
    dirk

  75. Thanks for the Tip.