Skip to content

Filed under Code

Updated Script for Tracking Outbound links In Google Analytics with jQuery

The outbound link tracker gets smarter by comparing hostnames instead of looking for http in the href.

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 improves behavior by comparing the link domain to the current page domain and if they are different, triggers the behavior. This is helpful for CMS or other tools that may generate full URLs including the protocol instead of just relative ones.

The new code

The selector skips links marked as excluded. The script saves the href to a temporary variable and compares the current hostname to the link hostname.

What is different

  1. First, you will 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 do not 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 hostname.
  3. You can see now where I look for the noAutoIcon value 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 and 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.