How to Send a Custom Event to Google Analytics 4 Using JavaScript
Tags: wordpress, googleanalytics, ga4, javascript
Published: 2021-01-20 11:05:45

---
title: How to Send a Custom Event to Google Analytics 4 Using JavaScript
published: true
description: How to send and view a custom event in Google Analytics 4.
tags: wordpress,googleanalytics,ga4,javascript
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/jjw4capcf11fyml417jg.jpg
---

## 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](https://developers.google.com/analytics/devguides/collection/ga4/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](https://dev-to-uploads.s3.amazonaws.com/i/xa87pyqig399cszpy4vw.png)

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

```css
li[id^='menu-item-'] > a
```

## 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.

```javascript
gtag("event", "MenuClick", {
  menu_item_name: name,
  menu_item_url: url,
});
```

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](https://gist.github.com/marklchaves/1ec73bdede21b85b59c37193492931ef).

```javascript
(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."
      );
    }
  });
})();
```

## The Result

### Viewing the Result in the Debugger

![DebugView](https://dev-to-uploads.s3.amazonaws.com/i/9xs7uvqwfpnrvddiv2zm.png)

### Viewing the Result in Engagement > Events

![Engagement > Events report](https://dev-to-uploads.s3.amazonaws.com/i/vt8ihsccsg3v2fdr0gr5.png)

### Creating a Custom Report in the Analysis Hub

![The custom menu click report in the Analysis hub](https://dev-to-uploads.s3.amazonaws.com/i/ed1s1ad4m87nl1fs1slj.png)

---

## Credits

The use case and workflow are based on Julius Fedorovicius' article [How to Track Custom Events with Google Analytics 4](https://www.analyticsmania.com/post/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.