jquerygoogle-analyticsevent-tracking

Tel link tracking with Google Analytics


I'm trying to track clicks on tel: links globally by sending an event to Google analytics. I would do it through tag manager because that would have been easier, but the client I'm working for is a franchise and the headquarters doesn't allow Tag Manager to be used.

I've come up with this code and have tried other variations but cannot get it to work.

jQuery("a[href^='tel:']").click(function(e){
    e.preventDefault();
        ga('send', 'event', 'Call Test', 'click', jQuery(location).attr('href'));
        phonenumber = jQuery(this).attr("href");
        window.location = phonenumber;
    });

It does successfully allow the call to happen but doesn't send the event to Analytics.


Solution

  • I was able to solve this and figure it out. Sharing code for others. Also, be sure to load jQuery from a CDN or internally before the code.

    $("[href*='tel:']").click(function(e) {
    
      e.preventDefault();
      var href = $(this).attr('href');
    
      // tel:
      if (href.toLowerCase().indexOf("tel:") >= 0) {
        eventCategory = 'Call';
        eventLabel = href.replace('tel:', '');
    
      }   
    
    gtag('event', 'Click', {
        'event_category': eventCategory,
        'event_label': eventLabel
      });
    
      ga('send', {
      hitType: 'event',
      eventCategory: eventCategory,
      eventAction: 'Click',
      eventLabel: eventLabel
      });
    
      setTimeout(function() {
    
    window.location = href;
      }, 500);
    
    });