Shoora
10/18/2018 - 1:47 PM

A shortened version of jQuery tracking with Google Analytics

A shortened version of jQuery tracking with Google Analytics

<script>
  $(document).ready(function(){
    var domain = document.location.host; //includes port if exists, whereas hostname does not
    var curPage = document.location.href;
    var downloadTypes = /\.(pdf|docx?|xlsx?|pptx?|mp3|wmv|avi|pub|mdb|zip|exe|rar|msi)$/i;

    //track outbound links with google analytics
    $('a[href^="http"]:not([href*="'+domain+'"])').each(function(event){
      //track the events: 1st = method, 2nd = category, 3rd = action, 4th = label, 5th = (int)value
      //http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
      $(this).click(function(event){
        //track an outbound link-click event
        //_gaq.push(['_trackEvent', 'Outbound', curPage, $(this).attr('href'),,true]);
        //ga('send', 'event', 'category', 'action', 'opt_label', opt_value, {'nonInteraction': 1});
        ga('send', 'event', 'Outbound', curPage, $(this).attr('href'),, {'nonInteraction': 1});
        if(!event.metaKey && !event.ctrlKey) {
          event.preventDefault();
          setTimeout('document.location = "' + $(this).attr('href') + '"', 3000);
        }
      });
    });

    //track file downloads
    $('a[href*="."]').each(function(event){ //best I could figure out... :-/
      var curHref = $(this).attr('href');
      if(downloadTypes.test(curHref)){
        $(this).click(function(event){
          //track an outbound link-click event
          //_gaq.push(['_trackEvent', 'Download', curPage, curHref,, true]);
          //ga('send', 'event', 'category', 'action', 'opt_label', opt_value, {'nonInteraction': 1});
          ga('send', 'event', 'Download', curPage, curHref,, {'nonInteraction': 1});
          if(!event.metaKey && !event.ctrlKey) {
            event.preventDefault();
            setTimeout('document.location = "' + curHref + '"', 3000);
          }
        });
      }
    });
  });
</script>