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:

  1. 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>
    	
  2. 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.
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.