Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Send a custom event to a Google Analytics 4 property using 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);
// => {
// 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 =;
let url ="href");
// 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) {
"Something wrong happened when setting up event handling for the menu items."

This comment has been minimized.

Copy link
Owner Author

@marklchaves marklchaves commented Mar 24, 2021

As seen on

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment