0% found this document useful (0 votes)
41 views

JavaScript-for-Google-Tag-Manager-Analytics-Mania-1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

JavaScript-for-Google-Tag-Manager-Analytics-Mania-1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

JavaScript for

Google Tag Manager


Taking your first steps

Created by
Julius Fedorovicius
Founder of Analytics Mania
[email protected]
@fedorovicius
I can teach you JavaScript for GTM
Hi, my name is Julius. I founded Analytics Mania in 2016. Since then, the blog
has grown to hundreds of thousands of monthly visits. Here I share my
knowledge, experiments, learnings related to web analytics, mainly Google Tag
Manager (GTM) & Google Analytics 4 (GA4).

I actively help others to learn Google Tag Manager with articles, videos, online
courses. "JavaScript for GTM" course is one of them. In that course course, you
will learn:
• JavaScript essentials for advanced work with Google Tag Manager
• How to write code, use it in Custom HTML tags and Custom JS
variables
• How to manipulate different data structures (e.g., adapt custom data
to GA4 ecommerce tracking)
• How to adapt the data layer to different vendors
• How to write custom event listeners
• How to work with the DOM (Document Object Model) and scrape it
• Other useful use cases of JavaScript in Google Tag Manager
You can learn more about my JavaScript for GTM course here. This course is
filled with practical examples and exercises.

2|Page
Table of Contents
#1. Introduction to JavaScript ........................................................................................... 4
What is JavaScript? .......................................................................................................... 5
How is JavaScript added to the website? ...................................................................... 5
#2. JavaScript essentials .................................................................................................... 9
#2.1. Statements ........................................................................................................... 10
#2.2. Variables............................................................................................................... 11
#2.3. Naming rules (and best practices) ..................................................................... 12
#2.4. Data types ............................................................................................................ 13
#2.5. Operators ............................................................................................................. 15
#2.6. Comments ........................................................................................................... 18
#2.7. String methods .................................................................................................... 19
#3. Using JavaScript in Google Tag Manager ................................................................ 21
#3.1. ECMAscript 5 vs ECMAscript 6 ........................................................................... 22
#3.2. Custom HTML tag................................................................................................ 23
#3.3. Custom JavaScript variable................................................................................. 27
#4. A fairly simple but powerful example of JavaScript in GTM ................................. 31
#4.1. How to extract part of the URL path ................................................................. 32
#4.2. Custom JavaScript variable................................................................................. 32
#4.3. This can be applied to other URLs as well ........................................................ 35
#5. Topics to learn next ................................................................................................... 36
#5.1. Functions and scope ........................................................................................... 37
#5.2. Array methods and loops ................................................................................... 39
#5.3. DOM – Document Object Model ....................................................................... 40
Final words........................................................................................................................ 42

3|Page
Chapter I

Introduction to JavaScript

4|Page
This e-book is for marketers and analysts who are at least intermediate Google Tag
Manager users and want to get started with JavaScript. If you are just starting with
GTM, this guide might be too difficult.

What is JavaScript?
JavaScript is the language of the web. Together with CSS and HTML, they form the
"Big 3".

HTML is responsible for the site's content, text, tables, headings, paragraphs, etc.

CSS is responsible for the style of that content. For example, it can be used to set
the font size, spacing, color, etc.

JavaScript is responsible for the interactiveness. If you submit a form on a page, it


must do something, right? For example, show a success message. Or hide an
element. Or redirect you somewhere. That is possible with JavaScript.

How is JavaScript added to the website?


First, let's start with how JavaScript is added to a site. There are three ways:

• Inline
• Embedded
• External

Inline JavaScript is included inside the HTML tag. For example, inline JavaScript can
push some information to the Data Layer when a link is clicked.

<a href=“#pricing“ onclick=“dataLayer.push({‘event’ : ‘link_click’})“>Click here</a>

In the example above, inline JavaScript is added as a value of the onlick attribute.
When this link is clicked, an event called link_click will be pushed to the dataLayer.

Inline JavaScript is not only related to click interactions. There are more types of
events where this can be used, e.g., when a mouse hovers over the website element,
when the form is submitted, etc.

5|Page
However, this is not a very scalable approach because there might be situations
when you have to copy-paste the same code repeatedly.

Embedded JavaScript. This way is much more flexible and scalable (in my opinion)
than Inline JavaScript. Embedded JavaScript can be added to HTML by surrounding
it with <script> tags.

In the code below, the red section is Embedded JS.

<head>
<title>Embedded JavaScript Example</title>
</head>
<body>
<h1>Welcome to My Web Page</h1>
<p id="message">Click the button to change this text.</p>
<button id="myButton">Click Me</button>

<script>
function changeText() {
document.getElementById('message').textContent = "Hello!";
}
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('myButton');
button.addEventListener('click', changeText);
});
</script>
</body>

You don't need to edit website elements individually to include JavaScript. Instead,
you can include a snippet of code in the head or body of the site, and then it will
work.

In fact, you are probably already familiar with it. When you are asked to install
Google Tag Manager or Google Analytics on a website, you must add a particular
code snippet to the source code of the website.

6|Page
That, my dear reader, is the embedded JavaScript. However, usually, parts of that
code also include external JavaScript.

External JavaScript. The third option is to have a separate JavaScript file on your
website and then reference it in the HTML code.

Your developers might create a separate JS file and then use it. Or your tracking
codes might refer to some external files. For example, the Google Tag Manager
container snippet loads the entire container that is available at
https://www.googletagmanager.com.

If you try to open the link of an external JavaScript file in the browser, you will see
the plain JavaScript code (without any HTML code).

7|Page
When the browser downloads the website's HTML code and starts rendering the
content, it will also download whatever is in that external JavaScript file and execute
it.

Why do developers often choose external JavaScript?

• It is cached by browsers (which speeds up page loading time)


• It is easier to maintain the code for them

8|Page
Chapter II

JavaScript essentials

9|Page
First, we'll start with several puzzle pieces, and we'll connect the dots later on. This
chapter might look "a bit dry" and filled with theory, but things will become clearer
soon.

If, on the other hand, you want to learn from highly practical examples and always
apply what you learn in real situations, take a look at my JavaScript course.

The philosophy behind that course is to rely heavily on the practical side of learning
and speed up the learning process.

#2.1. Statements

A JavaScript statement is an individual instruction that performs a specific action or


operation in a JavaScript program, such as declaring a variable, performing a
calculation, or executing a function.

For example:

• var price = 19.99;


• function calculateTax(price){ return price *1.21 }
• dataLayer.push({‘event’ : ‘link_click’});

Each statement in the code ends with a semicolon (at least in many cases).

If the code consists of just one statement, the semicolon is not necessary. Also,
some blocks of code don't require semicolons. For example, when you declare a
function or write an IF statement. Example:

if (totalSpent > 0) {
dataLayer.push({
"user_type " : "paying customer "
})
}

By the way, here is a quick side note. In most cases, JavaScript does not care about
white spaces. If I have code var price=19.99 and I have var price = 19.99, it's the
same code. Both will work just fine.

10 | P a g e
But there are also some situations where spaces matter. For example, when you
declare a variable (more on that later), you can use the keyword "var". So there
must be at least one space before and after it.

var price=19.99 will work.

But varprice=19.99 will not.

#2.2. Variables

A variable is a fundamental concept that you'll encounter frequently, especially


when working with Google Tag Manager (GTM). Variables in JavaScript allow you to
store and manipulate data, making your tags and triggers more dynamic and
powerful.

P.S. When I talk about variables in the JavaScript code, I don't mean "Google Tag
Manager" variables.

Think of a variable as a labeled container that holds a piece of information. This


information can be a number, a piece of text, or other data types. Once you've
stored something in a variable, you can use or change that information throughout
your script.

You use the var keyword to create (or declare) a variable in JavaScript. There are
also const and let variables, but in the context of this e-book, we'll be using var.
Later, I'll explain why.

Here's how you can declare a variable:

var productName;

In this example, we've declared a variable named productName. At this point, it


doesn't hold any value; it's just an empty container.

Once a variable is declared, you can assign a value to it using the = operator:

var productName;
productName = “Shoes”;

11 | P a g e
You can also declare and assign a value to a variable in one step:

var productName = "Shoes ";

After a variable has been declared and assigned a value, you can use it in your
script. For example:

var productName = "Shoes ";


alert(productName);

This script will display an alert box with the text "Shoes".

#2.3. Naming rules (and best practices)

When giving variables names, you must keep several things in mind:

• Spaces are not allowed in variable names. var product name will not work.
• Variable names (and JavaScript in general) are case-sensitive. productName
and productname will be treated as two separate variables.
• Variable names can contain letters, numbers, underscores (_) or $
• Keywords (e.g., var, function, return, etc.) that are reserved by JavaScript
cannot be used as variable names
• Variable names cannot start with a number

Also, follow these best practices:

• Variable names should be clear (var productPrice is much more precise


than var x)
• Be consistent with your naming convention. You should use camelCase (e.g.,
productName) or snake_case (product_name) and stick with this choice. If you
are working with an established code base, follow their selected naming
convention.

12 | P a g e
#2.4. Data types

JavaScript variables can hold different types of data. Here are the most common
types you'll encounter:

• string
• number
• boolean
• undefined
• null
• object
• array

A string is a sequence of characters used to represent text. Strings are enclosed in


single (') or double (") quotes. Strings can include letters, numbers, symbols, and
spaces.

var userName = "John Doe";


var greeting = 'Hello, world!';

A number in JavaScript can be an integer or a floating-point value (a number with a


decimal point).

var age = 30; // Integer


var price = 19.99; // Floating-point

Numbers are used for arithmetic operations like addition, subtraction,


multiplication, and division.

var total = price * 2; // this will multiply the price by 2

A boolean represents a logical entity with one of two values: true or false.

var isLoggedIn = true;


var hasPaid = false;

Booleans are often used in conditional statements to make decisions in your code.

13 | P a g e
if (isLoggedIn) {
console.log("User is logged in"); // if isLoggedIn is true
} else {
console.log("User is not logged in"); // if isLoggedIn is false
}

Undefined. A variable that has been declared but not assigned a value has the
value undefined.

var user;
console.log(user); // this will log undefined

Undefined indicates the absence of a value.

null is an assignment value that represents no value or no object. It's explicitly set
by the programmer to indicate that a variable should be empty.

var selectedProduct = null;

While undefined means a variable has been declared but not yet assigned, null is an
intentional absence of any object value.

An object is a complex data type that allows you to store collections of data and
more complex entities. Objects are created using curly braces {} and contain
properties defined by key-value pairs.

var user = {
name: "John Doe",
age: 30,
isMember: true
};

Objects are versatile and form the backbone of many JavaScript applications,
including Google Tag Manager.

14 | P a g e
An array is a special type of object used to store multiple values in a single
variable. You can think of them as lists. Arrays are created using square brackets []
and values are separated by commas.

var colors = ["red", "green", "blue"];

Arrays are helpful for storing lists of data and are commonly used in loops and
iterations. For example, when you are working with Google Analytics 4 ecommerce
tracking, products are temporarily stored in the "items" parameter. That parameter
is an array.

dataLayer.push({
event: "purchase",
ecommerce: {
transaction_id: "T_12345",
value: 72.05,
tax: 3.60,
shipping: 5.99,
currency: "USD",
coupon: "SUMMER_SALE",
items: [
{
item_id: "SKU_12345",
item_name: "Stan and Friends Tee",
price: 10.01,
quantity: 3
},
{
item_id: "SKU_12346",
item_name: "Google Grey Women's Tee",
price: 21.01,
quantity: 2
}]
}
});

#2.5. Operators

Operators in JavaScript are special symbols or keywords that perform operations


on operands (variables and values).

15 | P a g e
They are essential for performing calculations, comparisons, and other tasks in
your scripts. In this chapter, we will cover some of them: arithmetic, assignment,
comparison, logical, and more.

Please keep in mind that there are more operators than what is mentioned in this
e-book. My goal here is to give you an introduction, not to be an encyclopedia.

Arithmetic operators are used to perform mathematical calculations. Here are the
common arithmetic operators:

Addition (+): Adds two values

var sum = 10 + 5; // result: 15

Subtraction (-): Subtracts one value from another.

var difference = 10 - 5; // result: 5

Multiplication (*): Multiplies two values.

var product = 10 * 5; // result: 50

Division (/): Divides one value by another.

var quotient = 10 / 5; // result: 2

Assignment operators are used to assign values to variables. The basic


assignment operator is the equals sign (=), but there are also compound
assignment operators that combine arithmetic operations with assignment:

Assignment (=): Assigns a value to a variable.

var price = 10;

Addition Assignment (+=): Adds a value to a variable and assigns the result to that
variable.

var price = 10;


price += 5; // price is now 15 because 10 + 5

16 | P a g e
Comparison operators are used to compare two values and return a boolean (true
or false). These operators are essential for making decisions in your code.

Equal (==): Checks if two values are equal.

10 == 10; // true

It is commonly used in IF statements. For example, if the price equals 10, then
perform a certain action.

if (price == 10) { // checks if price equals to 10


console.log(price);
}

Strict Equal (===): Checks if two values are equal and of the same type.

10 === "10"; // returns false because 10 is a number, "10" is a string

Not Equal (!=): Checks if two values are not equal.

10 != 5; // true

Greater Than (>): Checks if the left value is greater than the right value.

10 > 5; // true

Logical operators are used to combine multiple conditions and return a boolean
value.

AND (&&): Returns true if both conditions are true.

age >= 18 && age < 65; // returns true if age is between 18 and 64

17 | P a g e
OR (||): Returns true if at least one condition is true.

age < 18 || age >= 65); // returns true if age is less than 18 or more
than 64

#2.6. Comments

Comments are notes or explanations added to your code that help you and others
understand what the code does. Comments are ignored by the JavaScript engine
when the code is executed, so they do not affect the functionality of your scripts.

You have already seen them multiple times in this e-book.

JavaScript supports two types of comments: single-line comments and multi-line


comments.

Single-line comments are used to comment out a single line of code or add a
short note. They start with two forward slashes (//).

// This is a single-line comment


var userName = "John Doe"; // Declare a variable to store the username

Single-line comments are great for brief explanations or for temporarily disabling
code during debugging.

Multi-line comments are used to comment out multiple lines of code or to add
detailed explanations. They start with /* and end with */.

/*
This is a multi-line comment.
It can span multiple lines.
Useful for more detailed explanations.
*/
var userName = "John Doe";

Multi-line comments are ideal for providing comprehensive documentation or


commenting out large code sections.

18 | P a g e
#2.7. String methods

JavaScript provides a variety of methods that allow you to manipulate and interact
with strings efficiently.

Even without knowing more complex topics (like loops or functions), you can
already achieve some valuable results with string methods.

There are also methods related to other data types (like array or number methods).
But in this e-book, we'll look at string methods to introduce you to this concept.

Even though there are many string methods, I will show you the ones I use the
most often.

The substring() method extracts a part of a string between two specified indices.

var transactionId = "id-abc123";


var extractedId = transactionId.substring(3,9)

The first number in the substring method means the index of the first letter (that
you want to pick). The index starts from 0. And then the 2nd number means the last
character you want to include.

The toLowerCase() method converts a string to lowercase letters, and the


toUpperCase() method converts a string to uppercase letters.

var message = "Hello, World!";


var lowerCase = message.toLowerCase(); // 'hello, world!'
var upperCase = message.toUpperCase(); // 'HELLO, WORLD!'

The split() is one of my most often used methods. It splits a string into an array of
substrings based on a specified delimiter.

Later in this e-book, I'll show you a practical example where it's very handy.

var message = "Hello, world!";


var words = message.split(" "); // ['Hello,', 'world!']

19 | P a g e
As you can see in the previous above, the code message.split("") returns an array
['Hello,', 'world!']. If you want to pick just the first word, you can declare the index of
that word.

var words = message.split(" ")[0]; // 0 returns the first value


'Hello,'

The replace() method replaces a specified value with another value in a string.

var message = "Hello, world!";


var newMessage = message.replace("world", "GTM"); // 'Hello, GTM!'

First, enter the string you want to replace ("world"). And then, you enter the replacement
("GTM").

Now, you know some JavaScript essentials. Let's take a look at how to apply that in
Google Tag Manager.

Keep in mind that…


In this e-book, we're just scratching the surface of JavaScript and its
application in Google Tag Manager. If you want to learn everything step-by-
step with clear instructions and many practical examples, take a look at my
JavaScript for Google Tag Manager course.

20 | P a g e
Chapter III

Using JavaScript
in Google Tag Manager

21 | P a g e
#3.1. ECMAScript 5 vs ECMAScript 6

JavaScript has evolved significantly over the years. It has various versions, each
bringing new features and improvements to enhance the language's capabilities.
These versions are standardized under the name ECMAScript (ES).

Two major versions are ECMAscript 5 (ES5) and ECMAscript 6 (ES6).

If you look for JavaScript code examples online, most of them will be using ES6.
However, there is one catch with Google Tag Manager.

Most of the features in GTM (Custom HTML tag and Custom JavaScript variable) do
not support ES6. Thus, your code snippets will have to use ES5.

The only place (at the moment) that supports ES6 in GTM is custom templates.

In this chapter, I wanted to give you a brief introduction to ES6 so that you would
know whether the code you found online is written in ES5 or ES6.

What is ES6?

ECMAScript 6 (ES6) introduced new features and syntactic improvements that make
JavaScript more powerful and easier to write. For example:

Let and Const. In ES5, variables can be declared only with the var keyword. In ES6,
you can also declare them with let and const variables. These new ways of
declaring variables also introduced a new scope in the code: block (but let's not
overwhelm ourselves with that, for now).

let x = 10;
const y = 20;

22 | P a g e
Arrow functions. In ES5, functions are declared using the function keyword.

// ES5
var add = function(a, b) {
return a + b;
};

ES6 introduced arrow functions, which provide a shorter syntax.

// ES6
const add = (a, b) => a + b;

So, if you see a code where the arrow => is used, that code is written in ES6.

There are many more updates/changes when we compare ECMAscript 5 and


ECMAscript 6, but those are more complex and might be challenging to understand
at your current learning stage. Thus, I will not mention them.

The abovementioned two changes are enough for you to recognize ES6 quickly.

Now, it's time to take a look at where custom JavaScript code can be used in Google
Tag Manager. We'll focus on the Custom HTML tag and Custom JavaScript variable.

#3.2. Custom HTML tag

One of the two ways (that I'll mention in this e-book) where you can insert your
custom JavaScript codes is a Custom HTML tag.

Usually, this tag is used to work with custom JavaScript libraries (e.g., Facebook
Pixel) or implement custom event listeners (e.g., AJAX or Vimeo listeners) that look
for particular interactions on a page (and then push particular data to the Data
Layer).

Creating a Custom HTML Tag

To create a Custom HTML tag in GTM, follow these steps.

23 | P a g e
Log into Google Tag Manager: Open your GTM account and select the container
where you want to add the tag. Click on the "Tags" section in the left-hand menu.

Click on the "New" button to create a new tag.

Click on "Tag Configuration" and select "Custom HTML" from the list of tag types.

In the HTML field, you can enter your custom HTML or JavaScript code. This could
be tracking scripts, custom analytics code, or any other script you need to run on
your site.

24 | P a g e
Keep in mind that this tag accepts HTML code. So, if you want to add Custom
JavaScript code, it must be surrounded with <script></script> tags.

Here's a sample code that you can test:

<script>
// Example JavaScript code
console.log('Custom HTML tag fired!');
</script>

Click on "Triggering" to set up when this tag should fire. You can choose from
existing triggers or create a new one. In this example, let's select "All pages".

Give this tag a name (e.g., “Test CHTML tag”) and save it.

P.S. For more custom code ideas, you can take a look at this article.

Now, let's test whether this code works. At the top-right corner of your Google Tag
Manager interface, click "Preview".

Enter the URL of your website. Click Connect.

25 | P a g e
After the preview mode has connected, go to the Tag Assistant tab and you'll see
that the tag fired. All this tag did was log the "Custom HTML tag fired" text in the
console.

If you want to see this, open the developer console in your browser. The steps
might vary on different browsers, but here's how you can open it on Chrome:

• For Windows users: CTRL + SHIFT + I


• For Mac users: ⌥ + ⌘ + J

Here, you should see the text printed out. If you refresh the page, the text will occur
again (because the tag fired again).

26 | P a g e
What about more practical examples? Where can a Custom HTML tag be
applicable? Here are several ideas for you to explore:

• Track embedded HTML5 audio players. Here you will have to copy the
listener code and paste it into the Custom HTML tag. That listener will look
for audio player interactions and push the interaction data to the data layer.
• Store a cookie in the visitor's browser
• Pre-fill hidden form fields. You can first store visitor's traffic source data in
cookies and then use custom JavaScript to insert that data in one or more
form fields.

#3.3. Custom JavaScript variable

Custom JavaScript variables are mainly used when you want to retrieve a particular
value from somewhere.

For example, you have a data layer variable {{transaction_id}} that contains the
transaction ID "id: abc123".

But what if you want to get rid of the "id: " at the beginning of the string?

Custom JavaScript can be used here to extract just a part of the text. Let's see how
that can be done.

In Google Tag Manager, go to the "Variables" section. Scroll down to the "User-
Defined Variables" section and click on the "New" button to create a new variable.

27 | P a g e
Click on "Variable Configuration" and select "Custom JavaScript" from the list of
variable types.

In the Custom JavaScript field, enter your JavaScript code. There are several
requirements here:

• The code must be an anonymous function (a function without a name)

28 | P a g e
• The function must return something (thus, there must be a return
statement)

Let's get back to our "transaction_id" example.

First, write the anonymous function with the return statement (we'll add more
things soon).

function(){
return
}

In this code, I will use the data layer variable (that I previously mentioned),
{{transaction_id}}. Let's include it as a variable in the code.

function(){
var id = {{transaction_id}};
return
}

First, I declared a JavaScript variable (id). Its name can be anything you want (as long
as it follows naming requirements and conventions). Then I assigned a Google Tag
Manager Data Layer variable to it (surrounded with {{}} ).

The id variable will get the data layer variable's value for that particular moment
when this variable is used. The value might be "id: abc123", "id: 837aib", etc.

Now, we want to get rid of that "id: " in the beginning.

Remember how I previously mentioned string methods in this e-book? Now, it's
time to use them because the value of the {{transaction_id}} variable will always be
a string.

There are various ways you can tackle this situation, but we'll use the replace()
method. We can look for "id: " string and replace it with nothing (""). In other
words, we'll delete the "id: ".

This could be done with the following expression:

id.replace("id: ", "")

29 | P a g e
Once the transaction_id is temporarily stored in the "id" variable, we use the replace
method. First, we look for that "id: " string. And if we find it, the code will replace it
with nothing "". Notice that there is a blank space between quotes.

In the custom JS variable's code, this would look like this:

function(){
var id = {{transaction_id}};
return id.replace("id: ", "")
}

And that's it! Now, this Custom JavaScript variable could be used in some tag, for
example, a GA4 purchase tag.

30 | P a g e
Chapter IV

A fairly simple but


powerful example
of JavaScript in GTM

31 | P a g e
#4.1. How to extract part of the URL path

Let's imagine that we have a URL of the following structure:


https://www.example.com/products/category_name/id, and we want to turn the
category_name into a GTM variable (knowing that the category name is always in the
2nd subdirectory of the Page Path.

How can we achieve that? Let's take a look.

#4.2. Custom JavaScript variable

In order to extract part of the URL path, we'll need to use a Custom JS variable. Go
to Google Tag Manager > Variables > New > Variable Configuration > Custom JavaScript.

In its code editor, type:

function() {

It will not do anything, yet (but this is just the start of our Custom JS variable). Now,
let's create a variable and name it pageUrl. Then, let's assign a value to it,
window.location.href:

function() {
var pageUrl = window.location.href;
}

window.location.href is a way to access the current URL of the page where the
user/visitor is. In the next step, let's return that pageUrl but only a part of it. We can
do that with the split() method, which splits a string (in this case, URL) into an array
of substrings. If you're new to this, we'll take a closer look.

function() {
var pageUrl = window.location.href;
return pageUrl.split();
}

32 | P a g e
But that's not all. We need to tell the split() method how exactly we want to split the
Page URL. If we go back to our example, we're working with
the https://www.example.com/products/category_name/id.

From that URL, we want to access the category_name. Since it is surrounded by


slashes ( / ), which could be used as a delimiter (separator) in our split method, let's
add that slash (surrounded by quotation marks).

function() {
var pageUrl = window.location.href;
return pageUrl.split("/");
}

As a result, this will return an array of all the parts that are in the URL. Here's a
more visual explanation. Before using the split() method, the Page URL looked like
this:

https://www.example.com/products/category_name/id

After using the method, the result visually would look like this:

As you can see above, the URL was split into a list of 6 items, starting with https and
ending with the id. The second item in the list is empty ("”) because there was
nothing between two slashes in https://.

We're almost there. category_name has been separated from the URL, all we need to
do now is to pick it from this array. This can be done by defining the index of that
array member. In our case, that number is 4. If you wanted to fetch the 3rd level of
the Page Path (the id), then you should have entered number 5.

33 | P a g e
Add it right after the split method (surrounded by square brackets):
function() {
var pageUrl = window.location.href;
return pageUrl.split("/")[4];
}

Done!

Save the Custom JavaScript variable in GTM, enable the preview and debug
mode and go to the page where you want to test this variable (make sure that the
URL contains something in the Page Path (at least 2 levels, a.k.a. folders, a.k.a.
subdirectories).

The expected result should look like this (of course, the value will be different in
your case).

34 | P a g e
Now you can use this variable wherever you need to. For example, send it as a
Content Group to GA4.

#4.3. This can be applied to other URLs as well


Don't limit yourself just to the Page URL. You can apply this to other addresses as
well, for example, Click URL, Video URL, etc. You just need to assign another value
to the pageUrl variable (in that Custom JavaScript).

Here's an example of how it would look if you wanted to access a certain part of the
Clicked URL.
function() {
var clickUrl= {{Click URL}};
return clickUrl.split("/")[4];
}

Instead of the window.location.href, we used the Click URL variable of GTM container
(just make sure that this built-in variable is enabled in your container). Then the
script will take the Click URL, split it (with "/") and then pick the item of which index if
4.

Keep in mind that the index in JavaScript starts with 0 (zero). Therefore, the 4th
element is actually the 5th one.

35 | P a g e
Chapter V

Topics to learn next

36 | P a g e
Your journey with JavaScript has just begun. But there are many topics waiting for
you ahead. Not sure where to start?

Let me help. I believe that these are the next topics you should dive into:

• Functions and scope


• Array methods and loops
• Document Object Model (DOM)

#5.1. Functions and scope

A JavaScript function is a block of code that performs a purposeful action. It takes in


an input, performs an action on the input and returns the desired output. You can
think of it as a factory machine that takes in one or more pieces of material and
outputs a finished product.

Functions are helpful since you can reuse them throughout your code. In the
example below, the function takes in the price of an item and the tax (as a decimal)
and returns the price after tax.

function priceAfterTax(price, tax) {


return price * (1 + tax);
};

When creating custom JavaScript variables in GTM, you will use anonymous
functions, meaning you do not name them. The example below comes from the
tutorial on how to track Vimeo players with GTM and GA4.

function () {
for (var e = document.getElementsByTagName("iframe"), x=0; x <
e.length; x++) {
if (/^https?:\/\/player.vimeo.com/.test(e[x].src)) {
return true;
}
}
return false;
}

37 | P a g e
If you look at the code in the Vimeo tutorial, you can see that it contains multiple
functions that work together to achieve the end goal of dispatching a Data Layer
event.

Conditional statements (or if statements) will enable us to define unique actions


that depend on the input meeting certain conditions. They are often used in
functions to return different outputs depending on the input.

In the below code, depending on the price of an item, the function returns a
boolean for whether shipping will be free.

function freeShipping(price) {
if (price < 100) {
return false;
} else {
return true;
}
};

Additionally, you can read more about the try…catch statement, which allows you
to test for errors in your code.

#5.1.1. Scopes

Scope defines the accessibility of a variable, object, and function from different
parts of the code. There are two main scopes for EC5: global and function (a.k.a.
local).

Global scope is defined outside of a function so that you can access it throughout
the code. Function scope is defined within a function, so it's only accessible there.

In the example below, you could not access the isFreeShipping variable outside of
the function since it is defined within it. However, you can reuse
the shippingCost variable and the addShippingCost function in other functions.

var shippingCost = 10; // Global scope


function addShippingCost(price) {
var isFreeShipping = freeShipping(price) // Function-Local scope
if (isFreeShipping) {
return price;

38 | P a g e
} else {
return price + shippingCost;
}};

When declaring variables in your code, consider scope carefully. If you need to
access a variable in multiple functions, declare it globally. For any variables you only
need within a specific function, set them within that function for better
organization.

#5.2. Array methods and loops

As we have already touched on, arrays are like lists of organized information,
making storing and arranging information from various data types easy. As with
strings, you can also manipulate and transform arrays with their own methods.

Some practical array methods include:

• .push() – Adds one or more elements to the end of an array and returns the
new length of the array (Google Tag Manager's dataLayer is using it)
• .pop() – Removes and returns the last element in the array.
• .find() – Finds and returns the first element in an array that meets the
specified condition without changing the original array.
• .slice() – Not to be confused with .splice(), this method returns the part of the
array between two specified indices as a new array.
• .map() – Returns a new array after calling a function on each element of the
original array
• .forEach() – Allows you to go through each element in an array and perform
an action using that element, but – unlike .map() – it doesn't return anything
(like a loop, which we cover next).
• .includes() – Returns a boolean based on whether an array contains the
specified element (this method is case sensitive).
• .filter() – Returns a new array containing each element in the original array
that met the specified condition.
• .reduce() – Returns a single element by applying the specified "reducer"
function on each element on the array (left-to-right).

It will take some time to get comfortable with all the different array methods, but
there are plenty of resources to help you out.

39 | P a g e
#5.2.1. Loops

Now, imagine that you have a basket of fruit, and each piece of fruit represents an
item in an array. Now, think of a loop as your hand repeatedly grabbing a piece of
fruit. With each grab, you can inspect, modify, or perform some action on the fruit.

One at a time, loops permit you to interact with the elements of an array. This
allows for an efficient way to perform repeated actions or make decisions based on
the contents of an array (or fruit basket).

Consider a scenario where you have an array of objects containing product


descriptions. Each object has a "price" key represented as a string with a dollar sign
($). Sending this data to a third-party analytics tool may pose problems, as these
tools typically prefer price without currency symbols.

How could array methods and loops help us here? The solution is straightforward –
you can utilize loops with the .replace() method to iterate through each object and
remove the currency symbol.

Loops and array methods elevate your ability to extract valuable insights from your
site. Continue exploring the depths of array methods and loops, and you may find
yourself feeling the need to buy a hacker’s hoodie soon…

#5.3. DOM – Document Object Model


The Document Object Model – mainly called the DOM – is a dynamic representation
of the structure and content of a website. You can imagine it as a tree-like structure,
with various branches showing how site elements are embedded within each other.

40 | P a g e
When you open a website, your browser downloads an HTML file from the
website's server and generates what you see on the site using HTML, CSS, and
JavaScript. Then, the DOM is built, allowing access to specific values from the
website with the help of JavaScript.

You may recognize the DOM from Google Tag Manager and Google Analytics 4.
While developers are not directly manipulating the DOM to implement GA4, your
site's embedded GTM tracking code contains JavaScript functions that interact with
the DOM to collect data.

If you've used Tag Assistant, this may look familiar:

When users visit your site, the Google Analytics 4 tracking code uses DOM events –
which "listen" for user actions – to track when events occur, like pageviews and
element clicks. You can add additional listeners to look for specific interactions on
your site, collect data on those interactions and send them to GA4.

Google Tag Manager also has existing features to use the DOM Element variable to
gather values from it. You can read more about it here.

41 | P a g e
Chapter VI

Final words

42 | P a g e
We just scratched the surface but you've taken an important step in mastering
JavaScript and its application within Google Tag Manager (GTM).

Some people try to learn this topic by themselves. They read the documentations
(or e-books like this one), do a lot of trial and error. In the end, they will waste a lot
of time. And time is money.

Others might enroll in some JavaScript course and learn there. But I have spotted
two problems with this approach:

• Generic JavaScript courses focus on developers who build websites and apps.
Not Google Tag Manager. After completing them, you will struggle with
applying that specific knowledge in GTM. More time will be wasted.

• Sure, there are JS courses related to GTM. But they have problems, too:
o Some courses require you to already have JavaScript fundamentals
(meaning that you must complete more courses)
o Others might give you fundamentals, but the learning process is
flawed. First, you will be bombarded with hours of theory. By the time
you start applying it in GTM, you will already have forgotten half of
what you learned before. Plus, they lack exercise.

What's my solution? A JavaScript course that's:

• tailored to Google Tag Manager


• full of practical exercises
• requires no prior JavaScript knowledge

If you want to become a GTM expert with sufficient


JavaScript skills, check out my JavaScript for Google Tag
Manager course. It includes:

• 10 Modules
• Practical tasks and a sandbox website to practice
• Lifetime 24/7 access to the course material
• Free updates
• Complete hand-holding and support
• And so much more!

Learn more about this course

43 | P a g e
This e-book was delivered to you by

Julius Fedorovicius
Founder of Analytics Mania
[email protected]
@fedorovicius

www.analyticsmania.com/

44 | P a g e

You might also like