Shoora
1/26/2018 - 2:16 PM

GA Event for anchors in jQuery 1.7+

GA Event for anchors in jQuery 1.7+

var $body = jQuery('body');
$body.on('click', 'a', function() {
  var $this = $(this),
    thisHref = $this.attr('href');

  if (thisHref.length
    && thisHref.substring(0, 1) === '#'
    && typeof ga === 'function'
  ) {
    ga('send', 'event', {
      eventCategory: 'Anchor',
      eventAction: 'click',
      eventLabel: $this.text().trim().substr(0, 140).trim(),
      transport: 'beacon'
    });
  }
});