(function() {
  "use strict";
  GOVUK.analyticsPlugins = GOVUK.analyticsPlugins || {};
  GOVUK.analyticsPlugins.externalLinkTracker = function () {

    var currentHost = GOVUK.analyticsPlugins.externalLinkTracker.getHostname(),
        externalLinkSelector = 'a[href^="http"]:not(a[href*="' + currentHost + '"])';

    $('body').on('click', externalLinkSelector, trackClickEvent);

    function trackClickEvent(evt) {
      var $target = $(evt.target),
          options = {transport: 'beacon'},
          href,
          linkText;

      if (!$target.is('a')) {
        $target = $target.parents('a');
      }

      href = $target.attr('href');
      linkText = $.trim($target.text());

      if (linkText) {
        options.label = linkText;
      }

      GOVUK.analytics.trackEvent('External Link Clicked', href, options);
    }
  }

  GOVUK.analyticsPlugins.externalLinkTracker.getHostname = function() {
    return window.location.hostname;
  }
}());

@@ -427,28 +427,34 @@
 ar $
-target = $(evt.targe
+link = getLinkFromEvent(ev
 t),%0A
@@ -514,145 +514,35 @@
 href
-,%0A          linkText;%0A%0A      if (!$target.is('a')) %7B%0A        $target = $target.parents('a');
+ = $link.attr('href'),
 %0A    
-  %7D%0A%0A      href = $target.attr('href');%0A
     
@@ -566,14 +566,12 @@
 im($
-target
+link
 .tex
@@ -727,16 +727,183 @@
  %7D%0A  %7D%0A%0A
+  function getLinkFromEvent(evt) %7B%0A    var $target = $(evt.target);%0A%0A    if (!$target.is('a')) %7B%0A      $target = $target.parents('a');%0A    %7D%0A%0A    return $target;%0A  %7D%0A%0A
   GOVUK.

Move externalLink DOM traversal to function