Skip to content

Instantly share code, notes, and snippets.

@marklchaves
Last active October 8, 2022 09:40
Show Gist options
  • Save marklchaves/1ec73bdede21b85b59c37193492931ef to your computer and use it in GitHub Desktop.
Save marklchaves/1ec73bdede21b85b59c37193492931ef to your computer and use it in GitHub Desktop.
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);
// 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."
);
}
});
})();
@marklchaves
Copy link
Author

marklchaves commented Mar 24, 2021

As seen on DEV.to.

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