Track Outgoing Clicks in Google Analytics with jQuery

Avatar of Chris Coyier
Chris Coyier on (Updated on )

Ian Pitts sent me this trick a while back and I’m just getting around to publishing it. Thank Ian!

Google Analytics (intro video here) is powerful stuff, but one notable lacking feature is data on outgoing clicks. If you are using jQuery, plop this code on your page and you’ll be tracking outgoing clicks in no time.

<script type="text/javascript">
  // <![CDATA[
    $(document).ready(function() {
      $("a[@href^='http://']:not(.noAutoLink)").addClass("offSite").attr('target', '_blank').bind('click keypress', function(event) {

        var code=event.charCode || event.keyCode;

        if(!code || (code && code == 13)) {
          if(pageTracker){
            var fixedLink = this.href;
            fixedLink = fixedLink.replace(/https?:\/\/(.*)/,"$1");
            fixedLink = '/outgoing/' + fixedLink;
            pageTracker._trackPageview(fixedLink);
          };
					
        };
    });
  // ]]>
</script>

Plain(ish) English:

  1. Target all href’s with http:// (Assuming that your internal links use relative file paths like they should)
  2. Except those with a class of .noAutoLink (Optional, but useful to specifically exclude links when you want to)
  3. It then adds a class of “offsite” (Also optional, but could be used as a CSS hook to show a sort of “external link” icon, especially if you plan to use target=”_blank”)
  4. Then it ads a target of _blank (Not XHTML compliant, but since it’s being added by script as needed, it doesn’t harm validation)
  5. Then it binds to both click and keypress events… so those using the keyboard instead of a mouse also get the action
  6. The if(pageTracker) part is what detects GA’s objects
  7. Then it does some regular expression magic to massage the href into something that can be tracked in GA
  8. A fake link is built that will appear within a fictitious /outgoing/ directory
  9. And lastly, GA is told to record a pageview for this new fake resource

Once you’ve been running this for a while (probably a few days, since Google Analytics isn’t very real-time), you can go into Content > Content Drilldown and find your /outgoing/ directory. Click that to check out your most popular outgoing links!

UPDATE:
Ian posted an update/improvement to this code on his blog. The new code doen’t just look for “http://” to determine if it is an outgoing link, but compares the hostnames to the current site. That way if you internally link with a full URL, it won’t be mistaken for an external link.