Advanced GTM Techniques - Custom Variables and Triggers for Insights

Advanced GTM Techniques - Custom Variables and Triggers for Insights

Advanced GTM techniques use custom variables like user-defined and data layer variables and triggers for deeper insights and precise and flexible tracking.

By: Mussarat Nosheen | 14 mins read
Published: May 31, 2024 9:00:00 AM | Updated: Jul 03, 2024 11:33:06 AM

Do you find implementing advanced GTM techniques for your website or social media complicated? 

35 % of retail companies share this sentiment where they find analytics and business intelligence challenging. 

3.8 million Google Tag Manager installs on e-commerce stores speaks volumes about its effectiveness in tracking businesses' performance online.

So, we have a detailed and easy-to-follow blog about setting up and using custom variables and triggers for deeper insights into GTM to help you.  

First, let us quickly review the Google Tag Manager components and then go straight to custom variables and triggers.

Get in touch to avail yourself of our Google Tag Manager Consultancy services.

Google Tag Manager Basic

Google Tag Manager (GTM) is a powerful tool that simplifies adding and managing website tags without extensive coding knowledge. As we delve into advanced GTM techniques, it's essential to understand the fundamentals that make this tool indispensable in modern digital marketing and analytics.

Brief Recap of GTM Fundamentals

GTM allows marketers and analysts to manage and deploy marketing tags (snippets of code) on their websites or mobile apps from a web-based user interface. It eliminates the need for direct developer intervention for each tag update, streamlining the workflow. 

Brief Recap of GTM Fundamentals

If you lack GTM implementation capabilities or feel your in-house capabilities need a more experienced helping hand, consider hiring the right GTM consultant for your business. 

Here's a quick overview of important GTM concepts:

  • Tags: These are snippets of code added to a website to collect information and send it to third-party tools such as Google Analytics 4, Facebook Pixel, or AdWords. Tags can serve various purposes, including tracking and analyzing conversions, remarketing, and gathering user behavior data.
  • Triggers: Triggers define the conditions under which tags fire. For example, you can set triggers to fire tags on page load, button clicks, form submissions, or specific interactions.
  • Variables: Variables are placeholders for values that GTM can use to configure tags and triggers. They can pull data from the website, such as page URLs, click text, or form field values, making tag management more dynamic and powerful.
  • Data Layer: The data layer is a JavaScript object that stores information sent to GTM. It acts as a bridge between your website and GTM, enabling structured and consistent data transfer.

Importance of GTM in Modern Digital Marketing and Analysis

In today's digital landscape, accurate and comprehensive data collection is crucial for making informed decisions and optimizing marketing strategies. GTM plays a vital role in this process by offering several significant benefits:

  • Efficiency and Flexibility: GTM significantly reduces the time required to implement and manage tags. Marketers can add, edit, and disable tags without modifying the website's code, resulting in faster deployment and more flexibility in managing marketing campaigns.
  • Enhanced Data Accuracy: By using GTM, marketers can ensure that tags are correctly implemented and triggered. It reduces the risk of errors and data discrepancies, leading to more reliable analytics and reporting.
  • Centralized Tag Management: GTM provides a centralized platform to manage all website tags. This centralized approach simplifies auditing, ensuring that tags are up-to-date and functioning correctly.
  • Improved Website Performance: Since GTM allows asynchronous tag loading, it helps improve website load times. Tags fire only when they meet specific conditions, reducing unnecessary script loading and enhancing the user experience overall.
  • Advanced Tracking Capabilities: GTM enables the implementation of advanced tracking techniques such as event tracking, conversion tracking, and user behavior analysis. This granular tracking provides deeper insights into user interactions and the effectiveness of marketing efforts.

Custom Variables

Custom variables in Google Tag Manager (GTM) are essential for tailoring your tracking setup to meet specific needs. These variables act as placeholders for dynamic values that can be used in tags, triggers, and other variables, allowing for more precise and flexible tracking. 

Custom Variables in GTM

Understanding and effectively utilizing custom variables can significantly enhance data collection and insights.

Definition and Purpose of Custom Variables in GTM

Custom variables are user-defined elements within GTM that store data and pass it to your tags and triggers. 

They allow dynamic data handling, making your tracking setup more robust and adaptable. The primary purpose of custom variables is to capture and utilize specific information that may not be directly available through standard GTM settings. 

This capability is crucial for implementing advanced tracking strategies and gaining deeper insights into user behavior.

Types of Custom Variables

The two main types of variables in Google Tag Manager include built-in and custom. Custom variables are known as User-defined variables in Google Tag Manager. 

Custom variables help enhance the precision and depth of your tracking setup, allowing for more sophisticated and insightful data analysis. 

They capture and utilize data tailored to your needs, providing a robust foundation for advanced GTM techniques and deeper insights into user behavior.

Once configured, these variables retrieve values from the DOM, URLs, cookies, and more. Some common types of user-defined variables include:

  • URL Variables: Used to extract specific parts of a URL, such as query parameters or hash fragments.
  • DOM Element Variables: Capture the value of a specific HTML element on the page, such as a form field or button text.
  • First-party Cookie Variables: Retrieve a cookie’s value set by your website.
  • JavaScript Variables: It allows the execution of custom JavaScript code to generate a value.
  • DataLayer Variables: Retrieve values from the GTM Data Layer, a structured JavaScript object that passes information from your website to GTM.

Creating and Implementing Custom Variables

Custom variables are a powerful feature in Google Tag Manager (GTM) that enables you to capture specific data points and pass them to your tags and triggers. This section provides a step-by-step guide on setting up custom variables and explores use cases to illustrate their practical applications.

Step-by-Step Guide on Setting Up Custom Variables

  1. Access GTM and create a new variable.
  • Log in to your GTM account.
  • Navigate to your workspace and click "Variables" in the left-hand menu.

Access GTM and create a new variable. to set up custom variable in GTM

  • Under "User-Defined Variables," click "New" to create a new variable.

2. Select the appropriate variable type (URL, DOM Element, JavaScript, or Data Layer Variable)  based on your needs.

Choose the custom variable type in GTM

3. Configure the variable.
  • Provide a descriptive name for your variable so its purpose is easily identifiable.
  • Configure the settings specific to the variable type you selected. For example, if you chose a URL Variable, specify which part of the URL to capture (e.g., query parameter, hash fragment).
4. Save and test the variable
  • Click "Save" to create the variable.
  • Use GTM Preview mode to test your variable. It allows you to ensure that the variable captures the correct data before deploying it live.

5. Once your variable is set up and tested, you can use it in your tags and triggers. For example, you can configure a tag to fire only when a specific variable value is present or use the variable to populate data fields in your tags.

Use Cases for Custom Variables in GTM

Custom variables can be employed in various scenarios to enhance your tracking and analytics capabilities. Here are some use cases:

1. Capturing User Interaction

User interaction tracking is crucial for understanding how users engage with your website. Custom variables can capture specific user actions, such as button clicks, link clicks, and video interactions.

For example, custom variables help create a click variable. 

To capture button clicks, create a DOM Element variable that targets the button's CSS selector. This variable can then trigger a tag whenever someone clicks the button.

Use Cases for Custom Variables in GTM

2. Tracking Form Submission

Form submissions are key conversion actions on many websites. Accurately tracking form submissions helps understand user intent and optimize the form for better performance.

For example, one can use custom variables to create a form variable to capture form field values.

Create a variable to capture the email address entered in a form and use it to fire a tag when the form is submitted, sending the captured data to your analytics tool.

3. Custom Dimensions for Google Analytics 4

Custom dimensions in Google Analytics 4 allow you to track additional data points beyond the default dimensions. Custom variables in GTM populate these custom dimensions.

For example, create a JavaScript variable to capture a specific value, such as user role (e.g., logged-in vs. guest). 

Configure a Google Analytics 4 tag to send this value as a custom dimension. This setup enables you to segment and analyze analytics data based on this additional dimension.

Follow these steps to set up a custom dimension:

I) Create a JavaScript Variable

Name: User Role

Type: JavaScript Variable

Code:

javascript

Copy code

function() {

  return window.userRole || 'guest';

}

II) Configure a Google Analytics 4 Tag

Select the Google Analytics 4 tag type.

Set Track Type to Pageview.

Go to More Settings > Custom Dimensions.

Add a new Custom Dimension with the Index number matching your GA setup and set the value to .

III) Set Up a Trigger

Configure a trigger to fire the tag on every page or specific pages where user role data is available.

Advanced Variable Techniques

Leveraging advanced variable techniques in Google Tag Manager (GTM) can significantly enhance your ability to manage and analyze data. 

This section covers using Regex and Look-up Tables for advanced variable management, with examples of dynamic event tracking and personalized user experience tracking.

Using Regex tables for Advanced Variable Management

Regular Expression (Regex) Tables are a powerful tool in GTM for pattern matching and transforming variable values based on complex conditions. 

Regex Tables allow you to map input values to output values using regular expressions, the sequences of characters defining search patterns.

You can set up a Regex Table in Google Tag Manager using the steps below.

  1. Go to Variables > New > Variable Configuration and select "Regex Table."
  2. Configure the Regex Table
  • Enable the "Enable Regex" option.
  • Enter the patterns and corresponding output values. For example, you can match URL paths or query parameters to categorize page types or user actions.

Example Use Case

Categorizing Page Types:

  • Pattern: ^/blog/.*
  • Output: Blog Page
  • Pattern: ^/product/.*
  • Output: Product Page
  • Pattern: ^/cart
  • Output: Cart Page

This setup helps categorize different types of pages, allowing for more granular tracking and analysis.

Implementing Lookup Tables to Simplify Complex Tracking

Lookup Tables in GTM can replace specific input values with predefined output values, simplifying complex tracking scenarios. They help manage vast data set transformations without writing custom JavaScript.

Setting Up a Lookup Table

You can set up a look-up table in Google Tag Manager using the steps below.

  1. Create a New Variable.

Go to Variables > New > Variable Configuration and select "Lookup Table."

2. Configure the Lookup Table

Define the input and output pairs. For example, map user roles to specific access levels or categorize product SKUs.

Example Use Case

Mapping Product SKUs to Categories:

  • Input: SKU123
  • Output: Electronics
  • Input: SKU456
  • Output: Home Appliances
  • Input: SKU789
  • Output: Books

This setup enables easy categorization of products based on SKUs, facilitating detailed analysis of product performance.

Examples of Advanced Scenarios and Solutions

Here are ways to use advanced GTM techniques to track your website or app performance. 

Dynamic Event Tracking

Dynamic event tracking captures user interactions that change based on context or user behavior. Advanced variable techniques, like Regex Tables and JavaScript Variables, can dynamically track these events.

Tracking Clicks on Dynamic Elements

  • Use a DOM Element Variable to capture the text of clicked buttons.
  • Set up a Regex Table to categorize these clicks based on the button text (e.g., "Buy Now", "Learn More").
  • Create triggers to fire tags based on these categories, enabling detailed tracking of user interactions with dynamically generated content.

Personalized User Experience Tracking

Personalized tracking involves capturing and analyzing data specific to individual users or segments, allowing for tailored experiences.

Tracking User Preferences:

Use a Data Layer Variable to capture user preferences stored in the data layer (e.g., preferred language, theme).

Implement a Lookup Table to map these preferences to specific actions (e.g., displaying content in the user's preferred language).

Use these variables to set triggers that fire tags that personalize the user experience, such as showing targeted ads or content recommendations.

Example Setup:

  • Data Layer Push

window.dataLayer = window.dataLayer || [];

window.dataLayer.push({

  'event': 'userPreferences',

  'preferredLanguage': 'en',

  'preferredTheme': 'dark'

});

  • Data Layer Variables
  • Variable Name: Preferred Language
  • Variable Type: Data Layer Variable
  • Data Layer Variable Name: preferredLanguage
  • Variable Name: Preferred Theme
  • Variable Type: Data Layer Variable
  • Data Layer Variable Name: preferredTheme
  • Using Variables in Triggers

Create triggers that fire tags based on the user's preferred language or theme of the user, allowing for personalized content delivery.

GTM Triggers

GTM triggers are conditions or rules that dictate when tags fire. They listen for specific events or interactions on your website and activate the corresponding tags when these events occur. 

This mechanism allows you to track user behavior, gather data, and implement various marketing and analytics tools effectively. 

Configure triggers appropriately to ensure that tags fire at the right moment and capture accurate and relevant data.

Types of Triggers

Here are the types of triggers you encounter in Google Tag Manager

1. Pageview Triggers

Pageview triggers fire tags based on different stages of a page's lifecycle. They are commonly used to track page visits and load events, providing insights into user navigation patterns and page performance.

Example Use Cases:

  • All Pages Trigger: It fires a tag on every page load. These are useful for general tracking purposes like deploying Google Analytics.
  • Specific Page Trigger: It fires only on particular pages, such as when a thank-you page loads after a form submission. It helps in tracking conversions or specific page interactions.
  • DOM Ready Trigger: Fires when the HTML of the page is fully loaded. It helps track elements that need to be present in the DOM.
  • Window Loaded Trigger: Fires when all resources, including images and scripts, are fully loaded. It is ideal for tracking events dependent on the complete page load.

2. Click Triggers

Click triggers activate tags based on user interactions with clickable elements on your website. They help track user engagement with buttons, links, and other interactive components.

Example Use Cases:

  • All Elements Click: It tracks clicks on any element and is helpful for broad click tracking.
  • Just Links Click: Specifically tracks clicks on hyperlinks, helping to analyze navigation patterns.
  • Specific Element Click: Fires a tag when someone clicks a particular element, such as a Buy Now button. It facilitates tracking valuable interactions and call-to-action effectiveness.

3. Form Submission Triggers

Form submission triggers track when users submit forms on your website. They are crucial for capturing lead generation and conversion events.

Example Use Cases:

  • All Forms Trigger: Fires a tag on submission of any form across the site. It is helpful to track general form submissions.
  • Specific Form Trigger: Targets specific forms, such as a contact or signup form. It helps monitor conversions from distinct form types and optimize form performance.
  • Enhanced Form Submission Trigger: Utilizes additional conditions like form validation and field completion before firing. It ensures data accuracy and relevance in form tracking.

4. Custom Event Triggers

Custom event triggers allow you to define and track unique events not covered by the standard trigger types. They provide flexibility to capture broader user interactions and site-specific actions.

Example Use Cases:

User-defined Events: Tracks events like video plays, downloads, or custom interactions defined in your data layer. It enables detailed and specific tracking tailored to the functionalities of your website.

  • E-commerce Tracking: Tracks e-commerce events like adding items to the cart, initiating checkout, or completing a purchase. It provides comprehensive insights into user behavior and sales funnel performance.
  • Interactive Features: It tracks interactions with dynamic elements like sliders, carousels, or interactive forms. It helps understand user engagement with advanced site features.

Example Setup for Custom Event Trigger:

Data Layer Push

window.dataLayer = window.dataLayer || [];

window.dataLayer.push({

  'event': 'customEvent',

  'eventCategory': 'Video',

  'eventAction': 'Play',

  'eventLabel': 'Homepage Video'

});

Creating the Custom Event Trigger
  • Navigate to Triggers > New > Trigger Configuration.
  • Select "Custom Event."
  • Set Event Name to "button1-click."
  • This trigger fires on: All Custom Events

Setting Up Advanced Triggers

Advanced triggers in Google Tag Manager (GTM) allow you to track complex user interactions and gain deeper insights into user behavior.

This section provides a step-by-step guide to creating advanced triggers and explores examples of complex trigger setups. 

A Step-by-Step Guide to Creating Advanced Triggers

Follow the steps shared below to create advanced triggers in Google Tag Manager. 

1. Access GTM and Create a New Trigger

  • Log in to your GTM account.
  • Navigate to your workspace and click "Triggers" in the left-hand menu.
  • Click "New" to create a new trigger.

2. Select Trigger Types

Choose the appropriate trigger type based on the interaction you want to track. For advanced triggers, common types include Scroll Depth, Element Visibility, and Timer.

3. Configuring the trigger Settings

Customize the settings specific to the chosen trigger type. For example, if you select Scroll Depth, configure the depth thresholds (e.g., 25%, 50%, 75%, 100%).

4. Add Conditions (If necessary)

Define additional conditions to refine when the trigger should fire. For instance, you might want the trigger to activate only on specific pages or under certain circumstances.

5. Save and Test the Trigger

  • Click "Save" to create the trigger.
  • Use GTM Preview mode to test the trigger and ensure it fires correctly based on your configurations.

6. Link the Trigger to Tags

Associate the newly created trigger with one or more tags to ensure it fires when it meets the trigger conditions.

Examples of Complex Trigger Set Ups

  • Scroll Depth Tracking

Scroll depth tracking helps you understand how far users scroll down your pages, providing insights into content engagement.

Here is how you can set up scroll depth tracking:

I) Create a New Trigger
  • Go to Triggers > New > Trigger Configuration.
  • Select "Scroll Depth."
II) Configure Scroll Depth Settings
  • Track vertical scroll depths.
  • Set depth thresholds (e.g., 25%, 50%, 75%, 100%).
  • Optionally, track horizontal scroll depths if relevant.

III) Save and Link to a Tag

  • Save the trigger.
  • Create a tag (e.g., Google Analytics event) and link it to the scroll depth trigger.
  • Element Visibility Tracking

Element visibility tracking allows you to fire tags when specific elements become visible in the viewport, which helps track interactions with content as users scroll.

Here is how you can set up element visibility tracking:

I) Create a New Trigger
  • Go to Triggers > New > Trigger Configuration.
  • Select "Element Visibility."
II) Configure Element Visibility Settings
  • Choose the selection method (e.g., CSS selector).
  • Specify the element you want to track (e.g., .cta-button).
  • Set visibility thresholds (e.g., 50% visibility).
  • Optionally, configure advanced options like minimum duration visible.

III) Save and Link to a Tag

  • Save the trigger.
  • Create a tag and associate it with the element visibility trigger.
  • Timer Triggers for Session Analysis

Timer triggers help track user behavior over time, such as time spent on a page or between interactions, aiding in session analysis.

Here is how you can set up timer triggers:

I) Create a New Trigger
  • Go to Triggers > New > Trigger Configuration.
  • Select "Timer."
II) Configure Timer Settings
  • Set the interval (e.g., 30,000 ms for 30 seconds).
  • Define the limit (e.g., 10 X).
  • Specify conditions for when the timer should run (e.g., on specific pages or for particular user segments).

III) Save and Link to a Tag

  • Save the trigger.
  • Create a tag (e.g., Google Analytics 4 event for engagement tracking) and link it to the timer trigger.

Example Scenario:

  • Scroll Depth Tracking:
    • Trigger: Scroll Depth
    • Depth Thresholds: 25%, 50%, 75%, 100%
    • Tag: Google Analytics Event
    • Event Category: "Scroll Depth"
    • Event Action: "Percentage", 25, 50, 75, 100
    • Event Label: ", contains, /blog/
    • Element Visibility Tracking:
  • Trigger: Element Visibility
      • Element: .cta-button
      • Visibility Threshold: 50%
      • Tag: Google Analytics Event
      • Event Category: "CTA Visibility"
      • Event Action: "50% Visible"
      • Event Label: ""
      • Timer Trigger for Session Analysis:
  • Trigger: Timer
    • Interval: 30,000 ms (30 seconds)
    • Limit: 10 times
    • Tag: Google Analytics Event
    • Event Category: "Timer"
    • Event Action: "30 Seconds"
    • Event Label: ""

Troubleshooting and Optimization

Finally, we have some common problems faced during GTM's advanced techniques implementation and how to avoid them.

Implementing advanced GTM techniques with custom variables and triggers can be highly beneficial but also comes with challenges. This section covers common issues in GTM, optimization tips, and tools to help you troubleshoot and refine your GTM setup for optimal performance.

Common Issues in GTM and How to Resolve Them

Let us cover the common issues encountered in GTM and ways to resolve those issues. 

Common Issues in GTM and How to Resolve Them?

GTM Mistakes

Solution

  1. Tags not firing

1. Double-check if the trigger conditions and variable conditions are working fine.

2. Incorrect data capture

2. Inspect data layer values in GTM preview mode.

3. Multiple tags fire unintentionally.

3. Refine trigger conditions and use exceptions.

4. Performance issues 

4. Audit tags, simplify custom JavaScripts, and prioritize using built-in functionalities. 

5. The preview mode is not working

5. Clear chase and cookies, use the correct container and publish all versions.

1. Tags Not Firing

Incorrect trigger configuration or variable reference can result in the tags not firing. 

To resolve this double-check the trigger conditions and ensure the variables used in conditions are correctly defined and populated.

2. Incorrect Data Captured

Implementing misconfigured variables or data layer issues can result in incorrect data collection.

Ensure the verification that your variables are correctly extracting the data from the data layer or DOM elements. Use GTM's preview mode to inspect the data layer values in real time.

3. Multiple tags Firing Unintentionally


Overlapping or overly broad triggers lead to the unintentional firing of multiple tags. 

Address it by refining your trigger conditions to be more specific. Use exceptions to prevent tags from firing in unintended situations.

5. Performance Issues

Excessive tags or complex custom JavaScript can cause performance issues. 

Audit your tags and remove any that are unnecessary to avoid these issues. Simplify your custom JavaScript and use built-in GTM functionalities where possible.

6. Preview Mode Not Working

Browser caching or issues with GTM configuration can result in the preview mode not working. 

You can resolve this by clearing your browser cache and cookies, ensuring you use the correct container version and that all changes are published.

Tips for Optimizing GTM Performance

Stick to industry best practices for GTM implementation and build on them to optimize your Google Tag Manager performance. 

  • Minimize Tag Load

Limit the number of tags fired on each page to reduce the load time. Combine multiple tracking needs into fewer tags where possible.

  • Use Asynchronous Loading

Ensure that tags are loaded asynchronously to avoid blocking the rendering of your web page.

  • Regular Audits

Conduct regular audits of your GTM setup to remove outdated or unnecessary tags, triggers, and variables.

  • Efficient Data Layer Usage

Use the data layer effectively to pass data to GTM. This method is more reliable and less resource-intensive than relying on DOM scraping.

  • Leverage Built-In Variables

Utilize GTM's built-in variables and avoid excessive use of custom JavaScript variables to improve performance.

  • Monitor Tag Firing Priority

Set tag firing priorities to ensure critical tags are fired first. This is particularly important for tags related to essential tracking and marketing pixels.

Tools and Resources to Debug GTM Implementation

These tools can help implement GTM debugging and ensure you collect all the right data. 

Tools and Resources to Debug GTM Implementation

1. GTM Preview and Debug Mode

Use the built-in preview and debug mode to test your tags, triggers, and variables before you publish them. This mode allows you to see which tags are firing and the values of variables in real time.

2. Google Tag Assistant

A Chrome extension that helps you validate the implementation of Google tags, including GTM. It provides detailed information on tag firing and identifies any errors or issues.

3. Data Layer Inspector+

Another Chrome extension that simplifies viewing the contents of the data layer. It helps debug data layer pushes and ensure the correct data is being passed.

4. Brower Developer Tools

Utilize the developer tools in your browser (e.g., Chrome DevTools) to inspect elements, monitor network requests, and debug JavaScript errors related to your GTM implementation.

5. Google Analytics 4 Debugger

A Chrome extension that logs detailed information about your Google Analytics hits directly to the JavaScript console. This is useful for ensuring your GTM setup sends the correct data to Google Analytics.

6. GTM Templates and Community

Explore the GTM templates gallery and community forums for pre-built solutions and advice from other GTM users. Templates help you quickly implement complex tracking setups without starting from scratch.

Conclusion

The blog discusses advanced Google Tag Manager (GTM) techniques, focusing on custom variables and triggers for deeper insights. 

The main features of a Google tag manager for tracking implementation include tags, triggers, variables, and the data layer.

Custom variables like the user-defined, JavaScript, and data layer track valuable interactions such as user interactions, and form submissions, and create custom dimensions in GA4. 

More advanced techniques to facilitate in-depth data collection and analysis include using Regex and Lookup tables. 

These tags fire when triggered. Pageview, page clicks, form submissions, and custom event triggers help analysts capture valuable interactions like scroll depth, element visibility, and timer triggers.

Users can maximize the benefits of Google Tag Manager by troubleshooting common mistakes and using optimization strategies, and tools to debug GTM. 

 

Like what you read? Learn more about Digital Analytics on our blog here.