Garrett Murphey

Ruby & JavaScript Development

Tracking Outbound Links with Google Analytics and jQuery

July 16, 2011

Here’s a quick event binding I wrote today for the site to track outbound links in Google Analytics using some jQuery selector trickery.

Update

I’ve been using this a lot, and, rather than copying and pasting it repeatedly, I decided to develop it into a real and true jQuery plugin. Download it and fork away!

(function ($) {
  $(function () {
    $('a[href^="http:"]:not(a[href^="http://' + document.location.hostname + '"])').click(function () {
      try { _gat._getTrackerByName()._trackEvent('Outbound Links', $(this).attr('href')); } catch (e) {}
    });
  });
}) (jQuery);

What’s going on here?

The selector’s doing most of the work here - looking for anchors linking to absolute URLs, and then basically filtering out anchors with absolute URLs pointing to the current document’s domain. When the outgoing links are clicked, we fire off the event tracking method in Google Analytics. This clicks will be categorized as “Outbound Links” and the anchor’s full URL will be tracked as an Action.


Other Recent Posts