This article is about Google Analytics 4 properties. If you're using a Universal Analytics property, refer to the Universal Analytics section of this help center.

[GA4] Measure button clicks and scroll depth

With some custom JavaScript, you can determine when you want to trigger events. This article describes how to write custom code for administrators with little to no programming knowledge.

Validate your code

As you write custom code for your site, use the Realtime and DebugView reports to instantly verify that you are collecting event data correctly. You can also use other reports and explorations to further dissect the data.

Measure button clicks

To send an event when a user clicks an "Add to cart" button on your site:

  1. Add this snippet to the <body> tag of your HTML page to display the button:
    <button id="addToCart">Add to cart</button>
  2. Add this snippet to your JavaScript to send the event within the function when a user clicks the button:

    document.getElementById("addToCart").addEventListener("click", function () {

      // Add event here


    This code identifies the button by its id and then triggers the function when a user clicks the button. By placing the event in the function, the event only triggers when the button is clicked.

As long as you use the same id for the button and getElementById() method, you can use these steps for any button on your site.

Measure scroll depth

If you need to measure scroll activity beyond what is provided as part of enhanced measurement, use the scroll depth trigger in Google Tag Manager. Writing a custom script using gtag.js is not recommended.

Was this helpful?
How can we improve it?
Clear search
Close search
Google apps
Main menu
Search Help Center