Google Analytics Custom Events: from clicks to reports

Google Analytics can track almost any event happening on your website. If you don’t know how to configure your tracking system to capture all sorts of events, don’t worry, I’m here to help!

The fact that we can track everything doesn’t mean that we should. Event tracking uses some bandwidth and, if abused, it can slow down the browser. But if done correctly and only for relevant events, the impact on the browser will be unnoticeable.

What kind of events can I track with GA?

Anything that JavaScript can detect on a webpage can be used to trigger a Google Analytics event. That includes HTML events like clicking on a button, scrolling the page, moving the mouse over an image. Google Analytics can also record events generated when certain specific conditions are met. For example, suppose we have a lead generation form asking our visitors how many employees their company has. We can set up a threshold on that value and generate a custom event every time the number of employees entered by in the input field is above the threshold. The custom event we created will be associated with the visitor filling the form and could be later used to assign the visitor to a specific segment of our audiences.

Do event tracking requires JavaScript

Basic events can be tracked without JavaScript by leveraging Google Tag Manager. For more specific custom events, JavaScript is the way to go. We don’t need a JavaScript guru to write the code to capture custom events on an HTML page. Given a little bit of time and patience, anybody can write the few lines of code required to track events on a web page. There are some important constraints: we must have access to the page JavaScript and HTML, or be able to inject (include) our JavaScript code to the page. Luckily, the most popular CMS systems, including WordPress, allow some JavaScript injection. You also need a regular Google Analytics account.
This article is based on Google Analytics 3, the most popular and widely used version of Google Analytics. Tracking custom events with GA version 4 is not different.

Tracking HTML events

HTML pages generate tons of events. Most of the time, these events are directly managed by the browser or ignored. With JavaScript, we can hijack some of these events and ask the browser to execute a snippet of our code every time the event occurs. Let’s consider, for example, a simple click event on a regular HTML button. The following is the HTML code for a button that offers to download a PDF document:

<button id='myButton'>Download PDF</button>

Using JavaScript, we can attach some code to the “click” event. Then, every time a visitor clicks on the button, the browser will automatically execute our JavaScript code. For example, the following is the JavaScript code to capture a click event:

const btn = document.getElementById('myButton')
btn.addEventListener(‘click’, () => {
    /* do something */
})


The first line of code gets the button from the HTML document, while the following lines associate some code to the click event. In this example, the code to be executed every time the button receives a click is a JavaScript comment. We are now ready to replace the JavaScript comment with a command for Google Analytics, as explained in the next sections of this article. As soon as we publish the page online, the Google Analytics command will start sending to GA servers information every time the button gets a click.

Is my website tracking code using ga() or gtag()?

When configuring Google Analytics to track visitors to our website, we were asked to include a few lines of code in every page we would like to track.

Depending on how long ago we added the tracking code to our website or blog, we could have two different types of tracking: ga() or gtag(). From our point of view, there is no substantial difference between the two. gtag() is the most recent version. Google now recommends using gtag() because it is compatible with the new Google Analytics 4. To find out which version is running on our website, we need to look at the source code of any of our pages.

If we see the following code, we are tracking page visitors with ga(), the older version of the tracking library.

<!-- Google Analytics -->
<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
   
    ga('create', 'UA-XXXXXXXX-X', 'auto');
    ga('send', 'pageview');
</script>
<!-- End Google Analytics -->

If instead, we see the following code, that means we are tracking visitors with the most recent version, called gtag().

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-X"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'UA-XXXXXXXX-X');
</script>
<!-- End Google Analytics -->

Capturing HTML events with ga() and gtag()

If our website is using ga(), then we can track all the clicks on our button replacing the JavaScript comment with a GA command as in the following JavaScript snippet:

btn.addEventListener('click', () => ga('send', {
    hitType: 'event', 
    eventCategory: 'ButtonClicks', 
    eventAction: 'DownloadPDF', 
    eventLabel: ‘Some event label’,
    eventValue: 0
}))

If our website is using gtag() then the GA command is slightly different:

btn.addEventListener('click', () => gtag('event', 'ButtonClick', {
        event_category: ButtonClicks,
        event_label: 'Some event label’,
}))

The difference between the two versions is purely syntactic. While we have to obey the syntax of the command, we are free to select the value of the fields EventCategory (‘ButtonClicks’), EventAction (‘DownloadPDF’), EventLabel (‘PdfRequest’), and EventValue (‘0’) based on out tracking goals.

Tracking non HTML events

The beauty of Google Analytics event tracking allows us to track events that are not directly generated by the HTML. Let’s consider as an example AcmeRugs, a fictitious online rug store that is offering its visitors a page where they can simulate placing a rug on the floor of a room. For simplicity, let’s assume that the simulated room is rectangular and that the visitor can control the width and length of the room via two input sliders. Input sliders are a standard feature of HTML where a numeric input is presented to the user as a draggable slider. For marketing reasons, the AcmeRugs store wants to tag all the users who tested a rug in a room larger than 100 sq. ft. Let see how they can do it. 

The simple panel to control the area of the room.

The HTML of the two sliders will be created by the following HTML code:

<input id='room-width' type='range' min='0' value='0' max='30' step='1'>
<input id='room-length' type='range' min='0' value='0' max='30' step='1'>

The computation of the total room area will be performed in real time by a snippet of code that acquires and then multiply the value of the two sliders. The code should be similar to the following snippet:

// Get the two sliders
const roomWidthElement = document.getElementById('room-width') 
const roomLengthElement = document.getElementById('room-length') 
// Funtion to compute the area
function updateArea() {
    var roomWidth = parseInt(roomWidthElement.value)
    var roomLength = parseInt(roomLengthElement.value)
    var roomArea = roomWidth * roomLength 
    /* do something with the roomArea value */ 
}
// Call the updateArea() function every time the sliders hange
roomWidthElement.addEventListener(‘input’, updateArea) roomLengthElement.addEventListener(‘input’, updateArea)

Now that we have a way to capture the value of the room’s area, we can finally check if the room is larger than 100 sq. ft. In that case, we want to record a custom event with Google Analytics. To do that, we extend the updateArea() function with a command to send a custom event to Google Analytics. The following is a JavaScript code with the revised function. We are using the ga() mode, but it should be very easy to update the script to use the gtag() syntax.

function updateArea() { 
    const LARGE_ROOM_AREA = 100 
    var roomWidth = parseInt(roomWidthElement.value)
    var roomLength = parseInt(roomLengthElement.value)
    var roomArea = roomWidth * roomLength
    // Send a Custom Event to GA
    if(roomArea > LARGE_ROOM_AREA) { 
        ga('send', { 
            hitType: 'event', 
            eventCategory: 'LargeRoom', 
            eventAction: 'LargeRoomSelected', 
            eventLabel: 'Room size = ' + roomArea.toFix(), 
            eventValue: 0 
        })
    }
}

How do custom events appear on GA reports?

Once the simple JavaScript tracking code is in place and the page is online, Google Analytics will start tracking the selected events. To make sure the tracking is working, we can check the Realtime section of Google Analytics under the Events report. The following image is a sample of the Events report for an interactive website page I’m tracking. You can recognize the Event Category and the Event Action values that will match the string values we selected when creating the JavaScript tracking code.

Google Analytics tracking custom events

Once the tracking has been tested and has been running for a while, we can explore a more complete report in the Behavior section under the Top Events report.

Behavior, Top Events report

Why are Custom Events important?

To fully appreciate the importance of custom events, let’s go back for a moment to the AcmeRugs example. Every time a visitor simulates a rug in a large room, our tracking code generates a custom event, and Google Analytics automatically associates that event to the current visitors.

So what can we do with this information? In Google Analytics, we can do at least two important things:

Create a Custom Segment.

A custom segment allows AcmeRugs to analyze the behavior and performance of all visitors with a large room in all GA reports and to compare their behavior and conversion rate with other visitors. AcmeRugs can easily create a Custom Segment by entering the condition Event Action = "LargeRoomSelected". The value for the condition must match the exact value used in the JavaScript code. The following image shows a Custom Segment creation with the necessary condition:

Creating a Custom Segment based on Event Action Value

Similar filters can be easily created to leverage other event’s attributes, like “Event Label,” “Event Category,” as well “Event Value.” In addition, multiple conditions on the event’s attributes can be combined with AND and OR operators to create more specific segments.

Create a Remarketing Audiences

If the marketing department of AcmeRugs wants to create a remarketing campaign to target visitors that have a large room, now they can do it. AcmeRugs only need to create a retargeting audience in Google Analytics and share the new audience with their Google Ads account.
To create the new audience, they open the Admin area of GA, select the “Property” they plan to use to build their new audience, then under “Audience Definition,” select “Audiences” and click on the “New Audience” red button. From there, AcmeRugs can define their remarketing audience as in the image below.

Creating a Retargeting audience that includes only visitors who generated a specific event.

Final thoughts

Custom events can be easily tracked from any webpage, but they require a few lines of code and some basics familiarity with JavaScript. For marketers with limited access to IT resources, it certainly means an additional effort. But the rewards are enormous. With custom events, we can analyze our data with specific segments and segment our visitors in vertical audiences.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s