This guide will teach you how to send custom events to Google Tag Manager (GTM). Custom events can track website interactions that aren't supported by GTM's standard methods. For example, you can set up a custom event to notify GTM that a user has clicked on a particular button.
For standard Google Tag Manager events and Universal Analytics Enhanced Ecommerce features, please consider using the Google Tag Manager Pixel app.
Instructions
Step 1 - Tracking a custom event
To notify GTM about a specific action performed on your website, you must send an event to the GTM dataLayer
whenever that action happens. The GTM dataLayer
is a JavaScript object that passes information from your website to your GTM container.
-
Open your project in any code editor of your preference.
-
Create a new function to push event data to GTM's
dataLayer
using the following code as a reference._10window.dataLayer = window.dataLayer || [];_10export default function push(event: any) {_10window.dataLayer.push(event);_10}
Remember to make the
dataLayer
variable available in thewindow
object before saving event data in it.
-
Go to the code line where the event happens and call your function, providing your event data as an argument. For example:
_10const data = e.data_10_10push({_10event: 'categoryView',_10categoryId: data.category?.id,_10}) -
Save and deploy your changes.
Step 2 - Testing the event
- Access your workspace in the GTM console.
- Click Preview.
- Test if the event trigger is working by performing the action associated with your event on the window opened by Preview.
Step 3 - Creating an event trigger
Once you've validated that the dataLayer
event is working properly, you'll need to set up a trigger so GTM can perform a specific action when your event is registered.
- Create a custom event trigger using the GTM console. Please refer to this guide for more information. Notice that you must enter the exact name of your data layer
event
in the Event name field. Considering our example, that would becategoryView
. - If applicable, create new variables of the Data Layer Variable type. Please refer to this guide for more information. Notice that you must set up new Data Layer variables only if you are sending additional information to your custom event. Considering our example, that would be
categoryId
.