April 12, 2024

The ContactSunny Blog

Tech from one dev to another

Track Custom Events with Google Analytics

2 min read

You’ve probably heard of Google Analytics before. We all use the tool to track various things on our websites. The tool provides information such as the location of users, page views, the kind of devices and browsers used by those users, the age group, and a lot more. But what if you want to track certain events which are specific to your website? Say you want to┬átrack how many people filled a form, or how many people clicked a link on your website?

Google Analytics provides an unbelievably simple way to track these custom events. It’s actually just one line of code to track such events. Let’s see how you’d do just this.

When you create a Google Analytics account, the tool gives you a small JavaScript code snippet to paste on your website. It’s suggested that you put this code inside the <head></head> tag of all the pages you want to track. The snipped looks something like this:

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

ga('create', 'UA-97204xxx-x', 'auto');
ga('send', 'pageview');

You don’t have to understand what that means or does. But notice that there is a new JavaScript function ‘ga()’ available to us now. We will use this to track custom events, just like the script above is using to track page views.

The signature of ga() is like this:

ga(command, hit_type, [fields]);

To track custom events, the syntax is like this:

ga('send', 'event', eventCategory, eventAction, eventLabel);

Here the parameters eventCategory, eventAction, eventLabel are your custom values. You don’t have to declare these anywhere in Google Analytics before you use. The categories will be created on the fly by Google Analytics as and when call the ga() function with these values. As an example, let’s consider we have two buttons – Event1 and Event2. On click of the Event1 button, we call the event1() function below, and on click of Event2, we call he event2() function below.

function event1() {
   ga('send', 'event', 'Event1', 'param1', 'param2');

function event2() {
   ga('send', 'event', 'Event2', 'param1', 'param2');

There are two events being triggered here, one for each button on the web page. So whenever you click a button, an event is triggered in Google Analytics. You can check it out in the Events sections under the REAL-TIME header. Here is a screenshot of the result.





Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.