Last Modified on September 4, 2024
Do you want to step up your measuring game?
If you’re using Google Tag Manager, learning how to use JavaScript, the programming language GTM is built on, will without a doubt help you achieve your GTM success goals.
Even though hearing that coding or programming is involved may be daunting, we’re here to guide and teach you the essential commands that you should know if you want to be more effective and work faster and safer in GTM.
In this guide, we’ll share with you five advanced techniques in JavaScript for Google Tag Manager that all digital marketers should know.
These are the top 5 must-know techniques for Google Tag Manager:
- Data Layer
- Data Layer Push
- Query Selector Method
- Google Tag Manager Object
- Immediately-Invoked Function Expression
1. Data Layer
Let’s start with a straightforward but powerful command to access the Data Layer.
A website typically has three layers: the presentation layer – what your users see, the applications layer – made up of tools connected to the website (e.g. Google Analytics and Google Tag Manager), and the Data Layer – where user-generated data gets stored.
The Data Layer provides a reliable way of collecting data from your website. The values inside this layer are often used by Google Tag Manager to pass information to your tags.
These include events, variables, and triggers that can be set up based on the variables’ values.
If you or your developer placed the Google Tag Manager container JavaScript snippet (gtm.js) in your website’s source code, then the Data Layer is automatically created.
Let’s say a friend sends you their website and wants you to check if their tracking is working. Since the Data Layer is the basis of GTM, the first step to checking their tracking deployment should be to look at the Data Layer.
A quick and convenient way to access the Data Layer, even without having access to the Tag Assistant, is to go to your browser’s Developer Tools.
If you’re using Google Chrome, go to the applications menu → More Tools → Developer Tools.
The developer tools for other browsers should be in a similar location. You can also use the keyboard shortcut Ctrl+Shift+I for Windows or Cmd+Shift+I for Mac.
Let’s move the developer tools pane to the side by clicking on the three dots at the top right corner, then the right-most icon for the Dockside option.
In the Console tab, type in dataLayer, then press Enter.
🚨 Note: JavaScript is a case-sensitive language. The dataLayer command should be entered with a small letter d, capital L, and with no spaces to properly access the Data Layer.
Clicking on the returned snippet will reveal all of the information stored in the Data Layer. Here, we can check if the right tracking information is properly stored.
When you click on the Add to cart button on any product, the Data Layer should be updated with the add to cart information.
To see the updated Data Layer information, we need to input the dataLayer command again. Here, we can see that there are now 7 items in the Data Layer, which includes the add-to-cart event.
💡 Top Tip: Pressing the up arrow key will copy the latest command you have typed in the JavaScript console.
Your troubleshooting can end here since you see that the Data Layer is set up properly or you can proceed and check other events.
If you need a quick way to check the Data Layer without extensions like the Tag Assistant, just type in the dataLayer command to your JavaScript console.
2. Data Layer Push
The next command attached to the Data Layer is dataLayer.push, which is used to store data in the Data Layer. This command uses an object with a key and value pair as an argument.
To check how it works, type in the following Google Tag Manager code example:
dataLayer.push({‘key’:’value’})
Press Enter. This should then return true.
If we invoke the dataLayer command again, we will see the key-value pair as the latest object in our Data Layer that we can then use in our tracking.
Now, when would it be useful to know a command like this? If you want to build a Data Layer and push custom information to it, then this command is something you need to learn how to use.
This command can be perfect if you only want to try out your tracking, and if you already have built tags that listen to a certain Data Layer event.
For example, the dataLayer.push command can send in a purchase event by invoking the next GTM code example:
dataLayer.push({‘event’:’purchase’})
You can then view the purchase event in the Tag Assistant, as well as the information that was brought in.
Inputting your dataLayer.push codes in the JavaScript console allows you to try them out beforehand and check if they are working properly before you implement them on your tags.
For example, if you wanted to install the enhanced eCommerce purchase tracking from the developers’ page, you can first try it out by copying the code and pasting it to the JavaScript console.
You can then see how this code affects the Data Layer based on the message you get.
Since this code returned true, it means it is working properly and will work fine when implemented in your tags.
However, if you try out another piece of code and it returns an unexpected error, it means something is not right in your code.
Knowing that there is an error beforehand allows you to correct your mistake before you send it to your developer and implement it on your website.
To fix this error, first, click on the error code at the right.
This leads us to where an error has been detected. We can see that one line has a red underline because the error was caused by the line before it. A comma was forgotten after the line which caused the whole thing to fail.
To fix this error, we simply need to go into the code again and put in a comma at the end of the affected line.
We’ll know if the code has been fixed if it returned true.
It is very handy to know about the dataLayer.push functionality to design your Data Layers, try out Data Layer syntax, and find errors, before you give it over to a developer and implement it on your website.
After pushing data/events to the Data Layer, you can then use the Data Layer event as a trigger and use the data to create your tags or variables.
🚨 Note: Check out our guide on scraping data with Chrome developer tools and GTM to learn how to inspect a website element and copy its JS path to create a GTM custom JavaScript variable.
3. Query Selector Method
The next technique we can use to utilize JavaScript for Google Tag Manager is the query selector method.
We have already discussed how you can pull data from and push data to the Data Layer, but what if the data you need for your tracking implementation is not in the Data Layer?
This method is very important for Google Tag Manager because it lets us select some aspects of the page that are present in the presentation layer.
The presentation layer is made up of elements on the page that the user sees, and is built on HTML and CSS. To proceed with this method, you do need to have some background in CSS so that you know how to select an element.
As we’re trying to keep this discussion as digestible as possible, knowing how CSS selectors work will help you better utilize the selector method for your website and meet your specific tracking needs.
Let’s say you want to get the price of a product on the product page. Right-click on this element and select Inspect.
This opens the developer tools on the elements tab where the HTML tag containing the inspected element is highlighted. Take note of the parent elements from the highlighted tag.
What the query selector does is that it finds an element on the page and returns it to you, so that you can do further operations on it and transfer it over to Google Tag Manager.
Let’s now utilize the query selector command and test how the CSS selector works. To start, let’s pull the elements that have the price class. We need to use the class selector inside the query selector command with the syntax ‘.classname.’
Type the following code in the console tab, making sure that the CSS selector is enclosed in parenthesis and single quotation marks:
document.querySelector(‘.price’)
Press Enter. If we hover over the HTML element that the command returned, the equivalent element on the webpage will be highlighted.
This is a good start since the correct area is highlighted. However, aside from the price, other things are also included. Therefore, we need to dive deeper and be more specific about the CSS selector we use.
Let’s use two type selectors in conjunction with the descendant combinator to change our CSS selector to “.price span bdi”. This selects the <bdi> elements inside the <span> element under the elements with class = “price”.
Our command should now be:
document.querySelector(‘.price span bdi’)
Checking and hovering over the element returned from using the command now only highlights the price with the dollar sign.
We can then only pull out the text inside the HTML element by adding .textContent at the end.
After testing it and knowing what it selects, we can then now use this CSS selector in different places inside GTM.
Let’s go over to Google Tag Manager and build something that will pull out that text exactly. For example, we can go and create a DOM element variable.
Go to Variables → New.
Click on Variable Configuration → DOM Element.
A DOM element variable has two options for the selection method: ID or CSS Selector. The one we are interested in is the CSS selector option since our HTML tag does not have an ID attribute.
Select CSS Selector for the selection method, then paste the CSS Selector we used inside the querySelector command.
We can also use the query selector method to create a custom trigger.
Head over to Triggers → New.
We’ll be creating an element visibility trigger. This trigger fires when a selected element becomes visible in the web browser’s viewport.
Click on Trigger Configuration → Element Visibility.
Like the DOM element variable, we’ll select CSS Selector for the selection method, and then paste the CSS Selector we used inside the querySelector command.
Under advanced settings, we can also use the CSS selector method, so that the trigger will fire only on Some Visibility Elements. Here, you can make the trigger fire when a certain variable matches CSS selector with the page element we picked.
💡 Top Tip: Always test your CSS selectors before using them in your variables, triggers, or tags. Use the query selector method inside your browser’s developer tools to ensure that it returns your desired results
4. Google Tag Manager Object
Next up, we have the Google Tag Manager object.
This is especially useful when you are looking again at the Data Layer. The dataLayer command we utilized earlier gives you access to the Data Layer, but not the internal model of Google Tag Manager. This is an object on the page itself.
Google Tag Manager has an internal representation of the Data Layer that can be different from the tags and variables we define.
When you want to access the internal data model of Google Tag Manager, you will first need to know your GTM container ID, which you can locate at the top of your GTM homepage.
The command syntax we will use to invoke the GTM object command is:
google_tag_manager[“Container_ID”]
When you type out the command in the console tab of your browser’s developer tools, your container ID can also pop up as a suggestion.
💡 Top Tip: Press the right arrow key to autofill your container ID without typing it or selecting it from the list.
The things you can do with the GTM object command are multifold, but what we have found is especially useful for looking at the Data Layer.
We can then use the get command to fill in anything that we would usually put into our Data Layer variable. What you usually put inside the data layer variable name can also be used inside the GTM object.
To illustrate how you can pull data from the Data Layer using the GTM object command, let’s go into the Tag Assistant → Data Layer and see what kind of elements we have.
For this example, let’s look at the ecommerce.currencyCode.
We would normally build a Data Layer variable out of this and go into the Tag Assistant and check if it’s working properly there. However, with the GTM object command, we can easily test it out without building the variable.
The command syntax should now be:
google_tag_manager[“Container_ID”].dataLayer.get(“key”)
Type this in the console tab, then press Enter. It should then return the corresponding value for our key as what was written in the internal data model.
Aside from testing Data Layer variables beforehand, we can also use this as an alternative to creating the variable altogether. Let’s see how this comes in handy by looking at an example.
In this GTM account, we have three types of variables: custom JavaScript, Data Layer variable, and DOM element.
If we look inside our Google Tag Manager custom JavaScript variable, we can see that we are utilizing the data layer variable in the code.
Instead of going through the additional step of creating a Data Layer variable to pull data from the Data Layer, we can simply use the GTM object command and pull data directly from the custom JavaScript variable.
To do this, first, go into the Data Layer variable and copy the contents from the Data Layer Variable Name field.
Before proceeding, make sure you have the built-in container ID variable enabled.
To check and/or enable this variable, go to the variables tab and in the Built-In Variables section, click Configure.
Here, you can find the Container ID under Utilities. Check it if you haven’t already.
We can then go inside the custom JavaScript variable and replace the Data Layer variable with the GTM object syntax we used earlier.
Instead of putting in our actual GTM container ID, we will use the container ID variable. The key we’ll use is what was inside the Data Layer Variable Name. This should work in the same way.
Now you might think that is this pretty much just a longer version of what we put in earlier and wonder what’s the point of all of this. By using the GTM object, there is no need to create multiple variables just to pull specific data from the Data Layer.
This is especially useful when you want to quickly pull and use data from the Data Layer in a single tag or variable. It might be easier to write out the relatively lengthier GTM object command and it won’t take as much space inside your GTM account.
That is how you implement the GTM object inside the variable. You can also utilize the same method inside your tags.
Using the GTM object command in the console tab will make your life easier because you can quickly check something and see how it’s resolved without having to create a Data Layer variable.
There are several other methods for how you can utilize the GTM object and one we want to highlight is how you can transform the Data Layer whenever the Data Layer provides the right information, but not in a format you could use.
5. Immediately Invoked Function Expression
The last technique for utilizing JavaScript for Google Tag Manager is the Immediately Invoked Function Expression (IIFE).
Where can this be useful and why should you use it? After going through the other JavaScript techniques in this guide, you may have noticed that we use certain keywords in the console tab that you have to remember to access specific things like the Data Layer.
These are reserved keywords that are hopefully not being used by any other programmer or script. When you have many different scripts running on your page, all of them are competing for the same space. Ideally, you should use unique variable names throughout.
Whatever command we have used in the console tab access data from the global scope. If you’ve used some reserved keywords in your tags, then you are effectively overwriting them.
For example, if we use the dataLayer command on a different website, it returns Hello instead of all the items we expect to see from the example earlier.
This happens because we have a custom HTML tag where we used JavaScript to overwrite the Data Layer.
🚨 Note: As much as possible, try to avoid using dataLayer or any other reserved keyword to name any of your variables.
If you have lengthy codes or haven’t written the code and copied it from somebody else, then ensuring that all your variables are using unique names can quickly become tedious and time-consuming.
A quick way to remedy this is by utilizing an immediately invoked function expression.
IIFEs are functions that are executed immediately after being defined. This creates a context for your code to run in that is closed off from the global variable space, eliminating the danger of overwriting anything from the global scope.
Simply place your code inside this snippet to use the IFFE:
(function () {
//your code
})();
Going back to our example, your code should look similar to this:
If we go back to the developer tools, trying out the dataLayer command should now return the snippet we expect to see, because our custom JavaScript is running in a completely different context.
💡 Top Tip: Always implement an immediately invoked function expression whenever you run a custom HTML code in your tags to avoid future conflicts.
FAQ
What is the Data Layer Push technique?
The Data Layer Push technique is used to store data in the Data Layer. It involves using the “dataLayer.push()” command with an object containing a key-value pair as an argument. This allows you to push custom information to the Data Layer and test tracking before implementing it in tags.
How can I use the Query Selector Method in Google Tag Manager?
The Query Selector Method is used to select specific elements on a webpage that are not in the Data Layer. It involves using CSS selectors to identify and retrieve elements from the presentation layer of the website. This method is useful for pulling data from elements on the page that the user sees.
What is the Immediately-Invoked Function Expression (IIFE)?
The Immediately-Invoked Function Expression (IIFE) is a JavaScript function that is executed immediately after it is defined. In the context of Google Tag Manager, it can be used to encapsulate and execute code within a function to ensure proper scoping and avoid conflicts with other scripts on the page.
Summary
We’ve covered the Data Layer, Data Layer Push, Query Selector Method, GTM Object, and IIFE, our top 5 recommended techniques to use JavaScript for Google Tag Manager.
Want to learn of a bonus sixth technique? Learn how to pull more contextual data from the user actions you track by checking out our guide on how to pull relative click data in GTM with a custom JavaScript variable.
Which other JavaScript techniques do you use to get the most out of your GTM tracking? Let us know in the comments below!