How to Pull Relative Click Data in GTM with a Custom JavaScript Variable

Do you want to supercharge your analytics and collect more data from each event?

With relative click variables, you can pull more contextual data from every user action you track in Google Tag Manager.

In this guide, we will learn the steps to set up a relative click variable using a Custom JavaScript Variable in Google Tag Manager.

An overview of what we will cover in this guide:

So let’s jump in!

What is Data “Relative to the Clicked Element?”

Just about every successful marketing campaign makes good use of button click tracking.

But tracking just button clicks leaves out so much valuable information.

Wouldn’t it be more useful if we could also track data from the web page where the interaction is happening? 

This is where data “relative to the clicked element” comes into picture.

Data relative to the clicked element includes any data on the web page that is not captured with normal click variables.

This is a really broad range of data. You can link almost any data to a click as long as it’s somewhere on the page.

For example, in an eCommerce shop, you can get details such as product name and product price relative to the “add-to-cart” click on a product page.

Let’s demonstrate this with a web shop that has Google Tag Manager installed.

A product page of our demo shop

Our first step is to create a variable relative to a click. 

Let’s take an example with an Add to Cart button on the product page. 

With a click trigger, you can access variables like Click Class, Click Element, Click ID, and Click Target. (Note that depending on how your button is configured, not all of these variables may be filled.)

Click Variables of a Click event in Google Tag Manager

In some cases, these variables are sufficient for your tracking needs. 

But sometimes these variables don’t translate well across different contexts on your website.

Some buttons that you want to differentiate may share variables. Conversely, you may have similar buttons whose variables don’t match up.

Plus, additional data such as price, product name, and more can drastically improve your data and analysis. And really, who doesn’t love more great data?

We can achieve all this with one simple tool: a Custom JavaScript variable. 

Preparing to Pull Data Relative to the Clicked Element

A custom JavaScript variable is the most versatile variable in your Google Tag Manager toolbox. It allows you to use JavaScript which powers GTM itself!

First we need to pull the data relative to the clicked element.

To demonstrate this concept, let’s collect the product name as data relative to the Add to cart click in our web shop.

This is a use case you can replicate on your own eCommerce website if you want to track which products users are adding to their carts (which can be different from products purchased).

Creating a Click Trigger

The first step is to create a simple click trigger.

A basic click trigger pushes data to the Data Layer any time a user clicks anywhere on our webpage.

So, we will create a trigger that fires on All Elements and All Clicks.

Choosing the option to fire the trigger on All Clicks in Google Tag Manager

Pulling Data Elements Using Browser Developer Tools

With the click trigger set up, our GTM is now registering clicks.

Our goal is to set up a relative click variable to transfer the relative data to the Data Layer. But to set up this variable, we’ll first need to fetch the clicked element and data relative to it from the DOM tree.

To find this data, we’ll need to crawl our DOM tree until we find our element, then pull the data relative to that element.

It’s not as complicated as it sounds! Let me show you how.

We’re going to use a technique that pulls the most recent Data Layer values, so start by entering GTM preview mode and clicking the element for which you want relative data.

With the click registered in the Data Layer, we can access the data we want using the gtm.element key.

Open your Chrome browser menu and go to More ToolsDeveloper Tools. 

Opening the Developer Tools of Google Chrome

Replacing the text ContainerID with your own GTM Container ID, you can type the following command in the Console panel:

google_tag_manager[“ContainerID”].dataLayer.get(“gtm.element”)

In this command, google_tag_manager gives us access to the GTM JavaScript object, while the Container ID in square brackets and double quotes give us access to that specific Container.

.dataLayer.get helps you query GTM elements that are retrievable from the Data Layer. (“gtm.element”) specifies which node in the Data Layer you want to extract.

The completed command returns the HTML object for the button you clicked.

Commands in the Console panel of Developers Tools to access the data stored in gtm.element

With this object identified, we can find other related data through the DOM tree.

Right-click the HTML object and select Reveal in Elements panel to view the object in its DOM context.

Since we want to pull the product name when users click this button, we’ll climb the DOM tree until we reach the element that gives us the product title on this page. 

In the Console panel, add .parentElement to your command to climb up the tree. We’ll repeat this addition to the command until we find the desired HTML object.

💡 Top Tip: Pressing the up arrow key in the console enters the previous command.

Once you reach the parent element that contains your desired data, you can use the CSS selector to select the correct child element. You can do this by adding querySelector(“”) to your command, with the parameter CSS selector inside the parentheses and double quotes.

Reaching the clicked element in the DOM tree structure

💡 Top Tip: You can hover your mouse over an object in the console to highlight it on the web page.

Almost done—the last step is to pull the text from your desired child element so that you can add it to a custom JavaScript variable. 

Add .innertext to the end of your command. If everything is working, this should return the desired relative data on the page of your clicked element.

We’ll use this completed command to finally build our custom JavaScript variable.

The Console returns the text of the product title that is within the element

Setting Up a Custom Javascript Variable

With all the prep work done, now comes the fun part: building a custom JavaScript variable for your relative data.

This is the most important part of this process, but it’s also the easiest.

Create a new Custom JavaScript variable, then add the following template into the Custom JavaScript field: 

function(){
return
}

Finally, copy and paste your completed command from the developer console into your variable configuration, right after return.

Setting up our Custom JavaScript variable in Google Tag Manager for data relative to the click

It’s important to know that a Custom JavaScript variable needs to have a function that returns a value. As long as your command accomplished this at the end of the last section, you should be good to go.

Our variable is now set up and ready! Let’s go ahead and test it.

Debugging

You should always test your configurations, but this is especially important when you’re building custom code.

Enter GTM’s preview mode on your website and click your targeted element. If this element appears on several different pages (like our Add to Cart button), you’ll have to do this multiple times.

If everything’s working correctly, your expected data should populate the field next to your custom variable.

But if there’s an error, your data will likely come back as undefined.

Product Title variable returns as undefined in the preview and debug console

So what’s going on when this happens?

Sometimes a variable comes back as undefined if the HTML markup has changed somewhere along the way.

It may also happen if there are some more elements in the product, or if the product itself is marked up differently. 

So how do we debug undefined variables?

First, you’ll need to enter your last command to check where you are on the DOM tree. 

This returns an error warning that will help us diagnose the problem.

Cannot read property ‘innerText’ of null error in the Console panel of developer tools

So let’s first remove our commands that fetch the data and start traversing the DOM tree again until we find our element.

This means from here we will move down the list of elements under the common parent element until the developer tool highlight includes the product title on the web page. 

Once we are there, we can again use the command .querySelector to get the element that matches our CSS Selector. 

And that’s it! The last step is to use the .innerText command to fetch the text content of this element. This will give us the product title on that web page. 

The Console returns the inner text of the product title in developer tools

Next, let’s adjust for this in our custom variable. 

Copy the final command and paste it into the Variable Configuration of Google Tag Manager.

Pasting the command from the developer Console and then Save the variable

To test this one more time, refresh your preview mode and return to the formerly-buggy click element.

Click on the Add to cart button to see if the variable is fetched correctly.

We should see the Product Title under the Variables menu of the preview and debug console. 

And if your product name appears this time, then congrats—you’ve successfully debugged your variable configuration!

cjs-Product Title is Ship Your Idea under the Variables menu of Google Tag Manager preview mode

But wait! Will this mess up the product titles of pages that were already working correctly?

Not really.

You should still double-check your other product pages, but these kinds of fixes shouldn’t interfere with your variable’s success.

With this we know that we have successfully adjusted our relative click variable. It will always pull out the correct product name relative to the click on the webpage. 

What’s more, you can apply this technique to all kinds of use cases. 

All you need to know is how you can pull out the right values from the DOM tree! After that, it’s just a matter of grabbing the right element by using .parentElement and .queryselector. 

Summary

This is how you can set up relative click variables. With a relative click variable, you can get additional information from your custom JavaScript variables.

And if you’re interested you can also set it up with scroll tracking or element visibility trigger. 

While this is done using a Custom JavaScript variable, you can improve your tracking even more with a variety of other GTM variables

Let us know in the comments below if this is something that you use often. Where might you use this technique on your own website?

JOIN US!

Master Data & Analytics with Measuremasters

Exclusive Courses & Workshops | Ongoing Troubleshooting | Support Resources, Tools & much more
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
eddie
eddie
8 months ago

what if I have more than one title, lets say in a footer

skye
skye
9 days ago

awesome contents! But why I couldn’t find demoshop.com at all?

now it's time to

Start measuring like a master

Itching to jump into the world of MeasureMasters? This is what you have to look forward to.