Google Analytics event tracking
You can add Google Analytics to any page by pasting the code Google provides into a snippet. You can also add event tracking to button clicks and form submissions with these steps:
- Add the following code into the same snippet, but after your Google Analytics code:
<script> document.addEventListener("DOMContentLoaded", function () { var elements = document.querySelectorAll('[id^="ga_"]'); elements.forEach(function (element) { var parts = element.getAttribute("id").split("_"); var eventName = parts[1]; if (element.tagName === "FORM") { element.addEventListener("submit", function () { if (element.checkValidity()) { gtag("event", eventName); console.log("Tracking GA Event: ", eventName); } }); } else { element.addEventListener("click", function () { gtag("event", eventName); console.log("Tracking GA Event: ", eventName); }); } }); }); </script><br>
- Give any button or form element a custom name that begins with "ga_". The text after "ga_" will be sent to your Google Analytics dashboard as the event name.