×

Top 5 Techniques in JavaScript for Google Tag Manager

Julian Juenemann

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.

GTM For Beginners

Sign up to the FREE GTM for Beginners Course...

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:

  1. Data Layer
  2. Data Layer Push
  3. Query Selector Method
  4. Google Tag Manager Object
  5. 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.

Accessing the browser 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.

Docking the developer tools pane to the right

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.

Entering the dataLayer command in the console tab

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.

Items stored in the Data Layer

When you click on the Add to cart button on any product, the Data Layer should be updated with the add to cart information.

Adding a product to the cart

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.

Updated Data Layer information containing 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.

Sample dataLayer.push command

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.

Sample key-value object successfully pushed to the Data Layer

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’})
Pushing a purchase event to the Data Layer

You can then view the purchase event in the Tag Assistant, as well as the information that was brought in.

Purchase event showing in the Tag Assistant

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. 

Enhanced eCommerce purchase tracking code

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.

Enhanced eCommerce purchase tracking code returning true

However, if you try out another piece of code and it returns an unexpected error, it means something is not right in your code.

Unexpected error in the copied 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.

Clicking on the error code

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.

Lines in the code where the error was detected

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.

Fixing the line of code causing the error

We’ll know if the code has been fixed if it returned true.

The true result signifying the error has been fixed

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.

Inspecting the price element on the product page

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.

Inspected element code in the developer tools pane

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.

querySelector command selecting all elements with the price class

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.

Improved querySelector command selecting the product price

We can then only pull out the text inside the HTML element by adding .textContent at the end.

Grabbing the text inside the element using textContent

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 VariablesNew.

Creating a new variable

Click on Variable ConfigurationDOM Element.

Creating a DOM element variable

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.

CSS selector method for the DOM element variable

We can also use the query selector method to create a custom trigger. 

Head over to Triggers New.

Creating a new trigger

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 ConfigurationElement Visibility.

Creating an element visibility trigger

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.

CSS Selector method for the element visibility trigger

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.

Matches CSS selector advanced settings

💡 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.

GTM internal representation of data

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.

GTM container ID

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.

GTM container ID automatically detected and shows 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.

ecommerce.currencyCode in the Data Layer

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.

GTM object command pulling data from the Data Layer

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.

Variable types inside Google Tag Manager

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.

Data Layer variable being used inside the custom JavaScript variable

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.

Copying the Data Layer variable name

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.

Configuring the built-in variables

Here, you can find the Container ID under Utilities. Check it if you haven’t already.

Enabling the built-in container ID

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.

GTM object used inside the custom JavaScript variable

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).

Immediately invoked function expression syntax

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.

dataLayer command returning hello

This happens because we have a custom HTML tag where we used JavaScript to overwrite the Data Layer.

Custom HTML tag overwriting the dataLayer command

🚨 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:

IIFE used inside the custom HTML tag

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.

Corrected dataLayer command

💡 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!

Julian Juenemann

Julian is the web analytics instructor and the owner of MeasureSchool. He has 10+ years of experience in teaching analytics tools such as Google Analytics, Google Tag Manager and Looker Studio. He founded MeasureSchool to help marketers with the data-driven way of digital marketing.

Related Posts

WooCommerce Google Analytics 4 Tracking blog featured image

WooCommerce Google Analytics 4 Tracking Guide

Eric Huguenin

Google Analytics 4 Cookieless Tracking blog featured image

Demystifying Google Analytics 4 Cookieless Tracking

Eric Huguenin

Google Tag Manager Lookup Table Variable blog featured image

How to Use Google Tag Manager Lookup Table Variable

Usman Qureshi

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

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.

Ready to take your digital marketing to the next level?

Subscribe to our newsletter and stay ahead with our latest tips and strategies.