DEV Community

Cover image for How to Send a Custom Event to Google Analytics 4 Using JavaScript
mark l chaves
mark l chaves

Posted on • Updated on

How to Send a Custom Event to Google Analytics 4 Using JavaScript

Intro

This article is a quick demo of how you can send a custom event to Google Analytics 4 (GA4) using just pure JavaScript.

I've only seen one other article describing something similar. But, that implementation used Google Tag Manager. I wanted to do the same thing using pure JavaScript instead.

You’ll also learn how to see custom events in GA4 via the DebugView, Events report, and a custom report.


The Scenario: Menu Clicks

Everything is an event in GA4. GA4 recognises 3 categories of events:

  1. Automatically collected events
  2. Recommended events
  3. Custom events

Google recommends using events from these 3 categories in the above order. Top-level menu clicks aren't in the first 2, so they're a great candidate for this tutorial.

All righty then. Let's track menu clicks by sending them as custom events to a GA4 property!

Identifying Menu Items in the Twenty Twenty Theme

In the WordPress Twenty Twenty and Twenty Twenty-One themes we can use the menu-item- ... ID values.

Using the menu-item-nn ID values to grab the menu items

Based on this HTML code, we can use this CSS selector for grabbing menu item elements.

li[id^='menu-item-'] > a
Enter fullscreen mode Exit fullscreen mode

The Code

Now that we know how to grab the menu items, we can hook them up with event listeners and callbacks.

Inside the event callback code, we'll need to add our call to gtag.js. It will look like this.

gtag("event", "MenuClick", {
  menu_item_name: name,
  menu_item_url: url,
});
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we send an event called MenuClick along with 2 parameters for the name of the menu item (i.e., menu item text) and the URL of the menu item.

The full algorithm is in the JavaScript snippet below and is available as a gist on Github.

(function () {
  if (typeof gtag === 'undefined') return;

  // Grab all the menu items on Twenty Twenty WordPress theme page.
  const menuElts = document.querySelectorAll("li[id^='menu-item-'] > a");
  console.log(`I found ${menuElts.length} menu items to process.`); // JavaScript template literal for printing inline JS expression.

  // If no menu items, bail.
  if (menuElts.length === 0) return;

  // Convert to an array so we can map over the array
  // if you don't want to use the spread syntax.
  // let menuItemsArr = Array.from(menuElts);
  // menuItemsArr.map((elt) => {

  // Spread and map.
  [...menuElts].map((elt) => {
    // Set up the listener and handler at the same time.
    try {
      elt.addEventListener("click", function (evt) {
        console.log("Sending menu click to GA4.");

        let name = evt.target.innerText;
        let url = evt.target.getAttribute("href");

        // DEBUG
        // evt.preventDefault(); // Don't navigate!
        // console.log(`Menu item clicked: ${name} ${url}`);

        gtag("event", "MenuClick", {
          menu_item_name: name,
          menu_item_url: url,
        });
      });
    } catch (e) {
      console.log(
        "Something wrong happened when setting up event handling for the menu items."
      );
    }
  });
})();
Enter fullscreen mode Exit fullscreen mode

The Result

Viewing the Result in the Debugger

DebugView

Viewing the Result in Engagement > Events

Engagement > Events report

Creating a Custom Report in the Analysis Hub

The custom menu click report in the Analysis hub


Credits

The use case and workflow are based on Julius Fedorovicius' article How to Track Custom Events with Google Analytics 4 posted on Analytics Mania.

Cover image: Custom scrambler with model Tara photographed by mark l chaves.

Top comments (0)