Updated Script for Tracking Outbound links In Google Analytics with jQuery | Blog | ISO-100

Updated Script for Tracking Outbound links In Google Analytics with jQuery

Chris Coyier recently posted to CSS Tricks with a snippet of some code I used on a recently released site. The code snippet uses Google Analytics and jQuery to automatically track outbound links.

At the time, that script looked at the existence of “http://” in the link URL to decide whether or not to attach the behavior. The new, updated script enhances behavior by comparing the link’s domain to the current page’s domain and if they are different, triggers the behavior. This is helpful for CMS or other tools that may generate full URLs including the http:// instead of just relative ones.

The New Code:

What’s Different

I’m not going to re-post the detailed description of what the script does. You can go view for that. I’ll just go over what’s different now:

  1. First, you’ll notice I use a different “not” clause in the selector. This is because on the updated site, I have separate “turn off” classes for different functionality. In this scenario, we only want to turn this tracking off if we don’t want automatic popups. The automatic off-site link icon creation is separate and I wanted that managed separately.
  2. Next, the code saves the href to a temporary variable and compares the current hostname to the link’s hostname.
  3. You can see now where I look for “noAutoIcon” to conditionally exclude the application of an “offSite” class, which displays a special icon next to that link.
  4. Finally, the exclusion class for “noAutoLink” is checked and the click/return event bindings are made. This is the same as the old script.

Enjoy! Let me know if you have any questions and by all means if you have improvements!

Links Mentioned