Google Analytics 4 Event Tracking

Is there a way to send an event to Google Analytics 4 when an appointment is booked? This would be really useful for setting the event as a conversion in Google Ads, so the campaigns can be optimized around it.

2 Likes

Hi there and welcome to the Community, @user33447 :waving_hand:

Nice idea, thanks for sharing! We’ll try to consider a built-in GA integration in the future, especiall if more users upvote this idea.

As for now, you can track clicks on the Submit Booking button using a GA code from our devs. Please add this part of the code to your website <head>:

<script async src="https://www.googletagmanager.com/gtag/js?id=G-ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-ID');
</script>

In the code above, you need to replace G-ID with your actual website ID for Google Analytics. This article will help you find your ID - Find your Google tag ID.

And then just add the rest of the script to the Custom JS field on the Settings tab of your widget’s settingsL

function sendEvent(config) {
  if (typeof ga !== 'undefined') {
    ga('send', 'event', {
      eventAction: config.action,
      eventCategory: config.category,
      eventLabel: config.label
    });
  }
  if (typeof gtag !== 'undefined') {
    gtag('event', config.action, {
      event_category: config.category,
      event_label: config.label
    });
  }
}

function isHitClass(e, selector) {
  return e.target && e.target.closest(selector);
}

function checkAndSendEvent(e, config) {
  const formContainer = e.target.closest(
    '[class*="form-layout__Container-sc"]'
  );
  if (!formContainer) {
    return;
  }

  const emailInput = formContainer.querySelector(
    '[class*="FormFieldLayout__Container-sc"] input[type="email"]'
  );
  if (emailInput) {
    const inputContainer = emailInput.closest(
      '[class*="FormFieldLayout__Element-sc"]'
    );
    const errorMessage =
      inputContainer &&
      inputContainer.querySelector('[class*="FormFieldLayout__Error-sc"]');
    if (errorMessage) {
      return;
    }
  }

  const phoneInput = formContainer.querySelector(
    '[class*="FormFieldLayout__Container-sc"] input[type="tel"]'
  );
  if (!phoneInput || !phoneInput.value) {
    return;
  }

  sendEvent(config);
}

document.addEventListener(
  'click',
  function (e) {
    if (isHitClass(e, '[class*="action-button__CenteredButton-sc"]')) {
      checkAndSendEvent(e, {
        action: 'appointment-booking-submit',
        category: 'Submit Appointment Booking',
        label: 'Submit Appointment Booking'
      });
    }
  },
  true
);

This article explains where you can find the info about clicks - Google Analytics 4 (GA4): Where to find my events - Elfsight Help Center

Please test it out and let us know if it worked :slightly_smiling_face:

1 Like