Tracking Email Copy and Click Events in JavaScript with Google Analytics

Introduction

Tracking user interactions on a website is crucial for understanding user behavior and optimizing your online presence. One common interaction that web developers often want to track is when users copy or click on email addresses. This can provide valuable insights into user engagement and help improve your website’s user experience. In this article, we will explore how to use JavaScript and Google Analytics to track email copy and click events on your website.

Setting up Google Analytics

Before we dive into the JavaScript code, make sure you have Google Analytics set up on your website. If you haven’t already, create a Google Analytics account and add the tracking code to your site’s HTML. This will give you access to Google Analytics’ event tracking functionality.

Tracking Email Copy Events

When a user copies an email address from your website, you can track this event using JavaScript. Here’s a simple code example:

function actionWithEmail(email = '') {
  const emailAndActions = [
    {
      email: 'sales@site.com',
      action: () =>
        gtag('event', '<action>', {
          event_category: '<category>',
          event_label: '<label>',
          value: '<value>',
        }),
    },
    {
      email: 'sales-1@site.com',
      action: () =>
        gtag('event', '<action>', {
          event_category: '<category>',
          event_label: '<label>',
          value: '<value>',
        }),
    },
    {
      email: 'sales-2@site.com',
      action: () =>
        gtag('event', '<action>', {
          event_category: '<category>',
          event_label: '<label>',
          value: '<value>',
        }),
    },
    {
      email: 'sales-3@site.com',
      action: () => alert('copyEmail_sales-3@site.com'),
    },
  ];

  const arr = emailAndActions.filter((e) => e.email === email);
  if (arr.length >= 1) arr[0].action();
}

document.addEventListener('copy', (event) => {
  actionWithEmail(event.target.outerText);
});

Tracking Email Click Events

To track when users click on email addresses, you can use JavaScript to attach event listeners to the email links on your website. Here’s an example:

const linkWithEmail = document.querySelectorAll('a[href^="mailto:"]');
if (linkWithEmail.length >= 0) {
  linkWithEmail.forEach((e) =>
    e.addEventListener('click', (element) => {
      actionWithEmail(element.target.outerText);
    }),
  );
}

Вам также может понравиться

About the Author: Vladimir Kusakin

Hi. I am web developer. For the past 9 years, I've been developing applications for the web using mostly PHP and Python. About me

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *