• Courses
    • Courses
    • Course bundles
  • Blog
  • Services
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • About
    • About
    • Contact
  • Login
  • Courses
    • Courses
    • Course bundles
  • Blog
  • Services
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • About
    • About
    • Contact
  • Login

May 30, 2017

7 Must-have Google Tag Manager Custom Variables

Every time I think “I know a LOT about Google Tag Manager”, a totally new horizon opens up, which leaves me thinking “Nope. I am still just a youngling and there’s so much left to learn”.

My other GTM breakthrough happened when I took a deeper dive into Google Tag Manager variables. I was successfully utilizing Data Layer variables, Constant variable, etc. But some of them were still a mystery for me.

In this blog post, I’ll show you my top 7 must-have Google Tag Manager custom variables that I use in the majority of my GTM containers.

#1. Page Title

To be honest, I still can’t understand why this variable isn’t available in Google Tag Manager by default. Although Google Analytics tracks Page Title by default, there are plenty of tools and use cases where page title (as a variable) would be very useful in Google Tag Manager.

Fortunately, it’s really easy to create one.

In your Google Tag Manager container, go to Variables > Javascript Variable and enter document.title

Page title - document.title variable

Now, enable GTM preview and debug mode and refresh the web page you’re currently working on. When Preview and Debug pane appears, click any GTM event (on the left side) and navigate to Variables tab.

You should see your newldy created Javascript variable – Page Title.

Page title variable in Google Tag Manager preview and debug mode

 

#2. ALT Text

If your website contains a lot of clickable images, you might want to track which ones are clicked the most.

But there’s one catch. It’s very possible that each image does not contain a unique ID or class, so how can you tell them apart with GTM?

Click Inspect element on one of those images.

inspect element

A pane with a lot of code will appear. Your image’s code snippet will be highlighted. Check whether that image contains alt attribute (like in the example below).

alt attribute

Although several images might have the same value of alt attribute, this still might be a good indicator of which image was clicked. For your information, alt attribute is not required, thus not all images will have it.

Anyway, if the website you’re working on has multiple alt attributes placed in the right way, feel free to use it as a Google Tag Manager custom variable.

How? It’s super easy, follow me.

In your Google Tag Manager container, go to Variables > Auto-event Variable and choose the following settings:

auto event variable - alt

Auto-event variable fetches a particular value of an element that a visitor interacts with. In this case, when a visitor clicks any website element, our newly created variable with look for alt attribute that belongs to that element.

If the element (i.e. image or link) does not have any alt attribute, the variable will return undefined value. If there is one, then it will fetch an attribute’s value.

Let’s test. After you create this variable, refresh the Preview and Debug mode, and a website you’re working on.

Click the image you’re willing to track. If it contains a link, do the click with CTRL or CMD key pressed. This way you’ll prevent the page from refreshing and losing all debug data in GTM Preview and Debug console.

Now, choose gtm.click GTM event and head over to Variables tab. You should see something like this:

gtm.click - alt

Pro tip: if you see no gtm.click event in GTM preview and debug mode, create a new trigger with settings Click > All Elements (within your Google Tag Manager container).

#3. Name of the Downloaded File

If you’re already tracking file downloads with GTM, you’re probably sending the entire URL to Google Analytics as Event Action (or Event Label).

For example, a user clicks a link to PDF file. You send https://www.example.com/files/guides/ultimate-guide.pdf as Event Action to Google Analytics. Although this works perfectly fine, the readability of data isn’t very convenient.

It would be much better if you could see only ultimate-guide.pdf in your GA reports, right? Fortunately, this is pretty easy. Just create a Custom Javascript variable with the following code:

function() {
 var filepath = {{Click Element}}.pathname.split("/");
 var filename = filepath.pop();
 var decodedFilename = decodeURI(filename);
 return decodedFilename.indexOf(".") > -1?decodedFilename:'n/a';
}

Important: before you test it, enable Click Element variable among built-in variables in your Google Tag Manager container.

Now, save the variable, refresh P&D mode and refresh the page you’re working on. Find a link to PDF or DOCX (or any other file) and click it. After gtm.linkClick event appear in the Preview and Debug pane, click it and head over to Variables tab.

downloaded file name variable in google tag manager

This variable returned the file name as a value. If the downloaded link is not an asset with a file extension, the script returns the ambiguous “n/a” string, which can be used in blocking rules, for example.

Pro tip: if gtm.linkClick event did not appear in Preview and Debug mode, enable a new trigger Clicks > Just Links.

 

#4. Mobile User

This custom variable lets you distinguish mobile users from desktop and tablets. It returns true if visitor/user is browsing with mobile device (tablets are not included).

In your Google Tag Manager container, go to Variables > Custom Javascript and enter the following code.

function() {
 var a = navigator.userAgent||navigator.vendor||window.opera;
 return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))
}

Custom Javascript - Mobile user

This script uses comprehensive regular expression (borrowed from detectmobilebrowsers.com) which returns a true or false value depending on whether or not the user is browsing with a mobile device.

Use case: you can display a notification with a special offer/discount only for mobile visitors. In this example you’ll need:

  1. a custom HTML tag which displays the notification or a popup (ask a developer to create one).
  2. and a page view trigger (see the example below). This means that a trigger will activate on every page load when a user is browsing with a mobile device.

Pageview - Mobile user

 

#5. Lookup Table for Multi-Domain Websites

I love lookup tables. Especially when it comes to managing multiple Google Analytics tracking codes. I could write a separate blog post about this type of variable, but I’ll try to be as swift as possible.

Google Tag Manager Ebook Bundle

Use case: You own 3 identical online stores but under different domains (example.com, example.de, and example.co.uk). They all have the same GTM container snippet installed, but you want to push their data to separate Google Analytics properties. How will you manage tracking IDs in your Google Tag Manager container?

The easiest way is to utilize a lookup table variable, which is a variable that has the value of another variable as input. It works like this: When [input variable] equals to _______, set [this output variable] to_______.

Google tag manager lookup table

Here’s a practical example to make things clearer. I chose Page Hostname as an Input variable and set the following rules:

  1. If Page Hostname equals to example.com, then show Google Analytics Tracking ID UA-XXXXXXX-11
  2. If Page Hostname equals to example.de, then show Google Analytics Tracking ID UA-XXXXXXX-22, etc.

Lookup table Google Tag Manager

I can then use this Lookup table variable in Google Analytics Tags as Tracking ID.

Pro tip: All conditions in Lookup table work under equals to. So if your website’s hostname can fully function with and without www, add both hostnames as list items in the Lookup table variable:

  • www.example.com –> UA-XXXXXXX-11
  • example.com –> UA-XXXXXXX-11

 

#6. UTM parameters

If you are actively using UTM parameters, you might want to fire particular tags based on particular values of utm_campaign, utm_source, utm_medium, etc.

Since I like keeping my variables, tags, and trigger in order, I usually create separate variables for each UTM parameter and then use them in trigger conditions.

Of course, you can simply create a rule where {{Page URL}} contains X or Y, having UTM parameters as variables helps me keep my container tidy.

You can easily turn UTM parameters into GTM variables by utilizing the URL variable. Just go to Variables > URL variable and create 3 variables with the following settings:

url variables in google tag manager

Another use case is to save values of UTM parameters in 1st party cookies.

URL variable is extremely versatile and can be used in a variety of situations. I have published a guide how you can make use of it.

 

#7. Screen Width

Similarly to Mobile User variable (No. 4 in this list), this variable gives us the ability to fire certain tags based on the user’s screen width.

Just create a Custom Javascript variable and paste the following code:

function() {
var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
return width;
}

Refresh you Preview and Debug made, and the website you’re currently working on. Choose any GTM event in the P&D pane and you’ll see the value of screen width in the Variables tab.

 

Google Tag Manager Custom Variables: Conclusion

This is just the tip of the iceberg. The more you learn about Google Tag Manager, the deeper the rabbit hole gets. In this blog post, I have shared my thoughts/knowledge on 7 Google Tag Manager custom variables that are my favorites.

I use them in almost every project/website I am working with. They empower me to create more complex triggers and be less dependent on developers.

What are your favorite Google Tag Manager custom variables? Let me know and maybe I’ll update this blog post with one of them.

Julius Fedorovicius
In Google Tag Manager Tips
32 COMMENTS
Daniele
  • May 31 2017
  • Reply

Awesome article! Thanks!

Marina Ofengeim
  • Jun 1 2017
  • Reply

Thank you very much!

Julius Fedorovicius
  • Jun 5 2017
  • Reply

You're welcome!

Jared Smith
  • Jul 20 2017
  • Reply

Absolutely do not use the Mobile User custom variable, I did and it resulted in my company's website giving all mobile users a 404 Error!!!!

    Julius Fedorovicius
    • Jul 20 2017
    • Reply

    It's difficult to comment on your issue without knowing the full context, however:
    1. I believe this could have been prevented with proper testing.
    2. Never rely on GTM to handle your link redirects or form submissions, and never use GTM to fix on-site issues that should be fixed in front-end code.

      Piotr
      • Apr 10 2018
      • Reply

      I agree with #1. Any code copied from any source should be tested, not blindly deployed to GTM for a production application.

      However, the context is not required here. The JS code for the Mobile User custom variable has bug. It fails the same way on any site I have tested it.
      * On the desktop device, it returns 'false', as expected.
      * On the mobile device, it also returns 'false', but also redirects the user to 'undefined'.

      Looks like the article's author took the code http://detectmobilebrowsers.com/ and removed sample URL from it. Also without bothering to even run it on the mobile device.

      It's sad, as generally I find the whole article very helpful.

        Piotr
        • Apr 10 2018
        • Reply

        The proper code should be:

        function() {
        var a = navigator.userAgent||navigator.vendor||window.opera;
        return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))
        }

          Julius Fed
          • Apr 10 2018

          You're right, this is unacceptable and it's my bad. I've updated the script and tested it on both devices.

          Thank you very much for pointing that out!

mostafa
  • Sep 19 2017
  • Reply

big thanks for this one :)

Jerome
  • Sep 22 2017
  • Reply

Very helpful. Thks

Anni
  • Jul 26 2018
  • Reply

Thank you Julius for this guide! I was wondering I have set up Lookup table to be able to track several GA properys using the same Tag manager. I now have a problem how I should set up the eventr tracking for outbound links. Ive tested to set the rule to exlude click url containing the domain, but when I add the other domains (from the different GA ID) the result is ofcours that I exlude outbound links to the other sites aswell which I dont want.

Do you have any idea how to solve this? Is there some way to tell Tag manager to look up what domain Im currently on and just exclude otbound links from that domain?

Thank you for a great post!

Best regads,
Anni

    Julius Fedorovicius
    • Jul 26 2018
    • Reply

    Hey, Sure. Import this GTM recipe. It automatically adapts to the current domain.

      Anni
      • Jul 26 2018
      • Reply

      Julius! You star! Thank you sooo much! I have been struggeling with this for days and here you swoop in solving my problem like that!

      Im forever grateful!!

      /Anni

Sebastijan Semiz
  • Sep 17 2018
  • Reply

Julius, thank you so much. Specialy the Lookup-Table variables are very helpfull.

Muhammad Raheel  
  • Oct 16 2018
  • Reply

I agree with #1. Any code copied from any source should be tested, not blindly deployed to GTM for a production application. Never rely on GTM to handle your link redirects or form submissions, and never use GTM to fix on-site issues that should be fixed in front-end code. Thank you very much i find the whole article very helpful.

Eric Brown
  • Jan 28 2019
  • Reply

Great article.

I have one question about your solution for passing UTM parameters to GTM. Would this solution work in the case of using GCLID auto tagging for Search or Doubleclick?

byron
  • Feb 5 2019
  • Reply

Regarding the first custom variable how could i change it if I am getting return type and Value undefined for the JavaScript Variable??

    Julius Fedorovicius
    • Feb 5 2019
    • Reply

    Two possible reasons:
    1. There's a typo in your variable settings.
    2. There is no title set for that page.

LHT
  • May 10 2019
  • Reply

Thank you!! I have a question about the UTM variables you created. Is it possible to pull the UTM data into Google Tag Manager after the user has navigated away from the URL with UTM terms?

Example:
User enters site via https://www.page1url.com?utm_source=source&utm_medium=medium&utm_campaign=campaign
User clicks on a second page within site: https://www.page2url.com
User clicks on a third page within site: https://www.page3url.com
User submits form

I have a GA event tag that fires when the user submits the form. Is it possible to also report the campaign terms with this tag?

Thank you!

    Julius Fedorovicius
    • May 10 2019
    • Reply

    Hey, you have two options:
    #1. Set cross-domain tracking (recommended)
    #2. Follow this guide https://www.analyticsmania.com/post/transfer-utm-parameters-google-tag-manager/ (but it will start a new session every time a visitor navigates from one website to another)

Federico
  • May 13 2019
  • Reply

I was using lookup tables in order to change the names of files like pdf downloads for better readability (yes, one by one). The solution you pointed in #3 is perfect for this! Helping save time.
Amazing article, thank you!

Jan Pieter
  • May 17 2019
  • Reply

Thanks for sharing this article!

I have a question on #3. I've implemented the custom javascript variable and I see the filename in the debug mode. However, all the spaces in the filename are converted to %20. Is there some javascript code I can add in order to replace the %20 with spaces?

Thanks in advance.

    Julius Fedorovicius
    • May 20 2019
    • Reply

    Hey, updated. The new code will also decode those weird things in the file name.

Christopher
  • Jul 22 2019
  • Reply

Hi and thanks for all yout great great tutorials :)
I have to deal with an issue about ALT text variable.
Everything works perfectly but the ALT text that I get is sometimes a translated string because of users web browser region parameters... So in my metrics I have lines with russian or chinese version of the alt attribute... Any idea about how to deal with it
Thanks a lot.
Chris

    Julius Fedorovicius
    • Jul 23 2019
    • Reply

    No, sorry. Never dealt with that. I'd say that you should then be using data-* attributes https://www.bounteous.com/insights/2017/07/07/track-more-click-detail-data-attributes-and-google-tag-manager/ (but this means that the developer's input is most likely needed

Thomas
  • Feb 10 2020
  • Reply

Awesome information that will save me a lot of time in the future, especially #5. I just onboarded a new client that has a .com and a .se site and I made two separate containers, making duplicates of all the tags... Had I known about lookup tables I could have save myself and my client some time. Oh well, next project...

Jizlia
  • Jun 10 2020
  • Reply

Thank you very much! I love your website, has saved my ass a couple of times.

Marco
  • Jun 12 2020
  • Reply

OMG! This article is fantastic!! Thank you very much!!!!!!!

Saral
  • Nov 9 2020
  • Reply

Are PWAs differently tracked? I want to map PWA with app & website, what's your thought?

Niall Thomas
  • Nov 6 2021
  • Reply

Hi there,

I need to capture the title of a google slides document or a google sheet when the URL is clicked but I can't do it. Any ideas?

Niall

    Julius Fedorovicius
    • Nov 9 2021
    • Reply

    hi, no, you can't do that

DigitalTriumphs
  • Jul 20 2022
  • Reply

Julius, thank you so much. Specialy the Lookup-Table variables are very helpfull.

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *

 

Hi, I'm Julius Fedorovicius and I'm here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey. Read more
Analytics Mania
  • Google Tag Manager Courses
  • Google Tag Manager Recipes
  • Google Tag Manager Resources
  • Google Tag Manager Community
  • Login to courses
Follow Analytics Mania
  • Subscribe to newsletter
Recent Posts
  • Introduction to Google Tag Manager Server-side Tagging
  • 3 Ways to Pull Data from Data Layer with Google Tag Manager
  • Cannot See the Google Tag Manager Option in Google Ads Conversion?
Analytics Mania - Google Tag Manager and Google Analytics Blog | Privacy Policy
Manage Cookie Settings