Last Modified on September 4, 2024
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.
Sign up to the FREE GTM for Beginners Course...
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:
- What is data “relative to the click element?”
- Preparing to pull data relative to the clicked element
- Pulling data elements using your browser’s developer tools
- Setting up a custom JavaScript variable
- Debugging
So let’s jump in!
What is Data “Relative to the Clicked Element?”
Data relative to the clicked element includes any data on the web page that is not captured with normal click variables.
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.
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.
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.)
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.
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 Tools → Developer Tools.
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.
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.
💡 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.
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.
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.
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.
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.
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.
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!
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.
FAQ
How can I set up a relative click variable in Google Tag Manager (GTM)?
To set up a relative click variable in GTM, you can follow these steps:
1. Create a click trigger that fires on all elements and all clicks.
2. Use your browser’s developer tools to fetch the clicked element and its related data from the DOM tree.
3. Create a custom JavaScript variable in GTM and write a function that retrieves the desired data based on the clicked element.
4. Test and debug the variable to ensure it returns the expected data when the trigger is fired.
How do I set up a custom JavaScript variable in GTM?
To set up a custom JavaScript variable in GTM, you can:
1. Create a new Custom JavaScript variable in GTM.
2. In the variable configuration, enter the JavaScript code that retrieves the desired data relative to the click.
3. Ensure that the JavaScript code returns the data by using the return
statement.
4. Save the variable configuration.
How do I fetch data elements using browser developer tools?
To fetch data elements using browser developer tools, you can:
1. Enter GTM preview mode and click on the element for which you want to retrieve data.
2. Open your browser’s developer tools (e.g., Chrome Developer Tools).
3. Use the command google_tag_manager["ContainerID"].dataLayer.get("gtm.element")
in the console to access the clicked element.
4. Traverse the DOM tree and use commands like .parentElement
and .querySelector
to locate the desired data relative to the clicked element.
5. Verify that the commands return the expected data.
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!
If you’re interested in more JavaScript content, check out our handy guide on the 5 advanced techniques in JavaScript for Google Tag Manager.
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?
what if I have more than one title, lets say in a footer
you would need to adjust this technique accordingly. There is no one-size fits all. Another option would be to change your HTML
awesome contents! But why I couldn’t find demoshop.com at all?
because it runs on my computer and not on the internet. Within our paid programs we provide our students a demoshop to implement and try out their tag deployments.
Hey thanks for your tuto,
When I enter in the console :
google_tag_manager[“GTM-XXXXXX”].dataLayer.get(“gtm.element”)
i got an undefined result.
Do you have any idea why ?
Thanks
XXXXX is a placeholder. Enter your real GTM ID (I don’t know it, you find it in your account or tracking code)
Hello Julian ! Thank you very much for this tutorial ! I’d like to do the same thing. But my element is a select element with different options. I’d like to know if there is a way to include an if condition in the JS with your method.
Thank you for your answer !
yes, you can do it in JS. How? That depends on your HTML
Hello Julian,
Thank you very much for your answer ! I tried your method and thanks to you I succeeded. But I have a new question. When I click on the element I want to get the value, the value appears. But when I click or do someting else on the page. the value disappear. Is there a way to keep the value in the dataLayer ?
I’m sorry for all these questions and I thank you for your work !
Hey Julian,
Great tutorial, thanks!
I just tried your concept but simply used {{Click Element}} instead of google_tag_manager[“GTM-XXXXXX”].dataLayer.get(“gtm.element”).
Seems to be working fine.
Main upside is more generic and transportable across accounts.
Any downsides?
This is very helpful. Thank you.
you are the king
Hey Julian, for my use case, I am actually only trying to capture specific text within the innerText (for PII reasons). For example, below is what is captured in the innerText section, but ideally I would only want to capture the specific text that showcases the Contribution ID, Date, and Amount. Is it possible to segment out the text that can be captured?
“‘Dear Drew,\n\nThank you for your generous contribution.\n\nPlease print out this contribution confirmation page for your records.\n\nContribution Information:\nContribution Confirmation ID: 95973340\nContribution Date: 04/08/2022 2:33 PM Eastern Daylight Time\nContribution Amount: $3.00\n\”
Yes, you can do this by using RegEx.
Perhaps that is an obvious one, but if the console throws an error for
then use ‘ instead of ”