Google Tag Manager Custom JavaScript Variable examples

ShareShare on Facebook7Tweet about this on TwitterShare on LinkedIn2Share on Google+4Buffer this page

Google Tag Manager Variables are awesome and easy to set, but Custom JavaScript Variables do require some JavaScript knowledge and time to write them. So I wanted to have a place where I could store and share scripts I liked or use most frequently.

Lowercase value

Use case: Well, to lowercase something :)
Custom JavaScript Variable:

function () {
 return {{Click Text}}.toLowerCase();
 }

Parse a string and return a specific element

Use case: Split clicked element classes by empty space and return a second class (remember, counting starts from 0) to use as Event Action or Label. So for a class=”cta-btn next yellow-button” this will return “next”. Similarly, can parse Page or Click URL Path by “/“ to get a specific directory.
Custom JavaScript Variable:

function () { 
 var value={{Click Classes}}.split(" "); 
 return value[1]; 
 }

To get the last element use: 

function () {
 var value={{Click Classes}}.split(" ");
 return value[value.length-1]; // or return value.reverse()[0];
 }

Get form field value

Use case: Get the value of a form field to check if not empty (see below) and/or pass the value to Google Analytics or other Tags. Theoretically, this also could be done with Auto-Event Variable, but after some experiments I found only this solution working.
Custom JavaScript Variable:

function () {
 return document.getElementById(“email").value;
 }

Get parent element inner text

Use case: You want to get the Clicked Element text, but it is not inside the clicked element and/or a link. For example <h3><span class=”icon”></span>Label</h3>. You need to look at the parent element h3 to take the “Label” text.
Custom JavaScript Variable:

function () {
 return trim({{Click Element}}.parentNode.innerText);
}

Check if value is not empty

Use case: Check if a Variable is empty to use as Trigger condition for specific Tag launching or blocking. Return false if empty, true is not.
Custom JavaScript Variable:

function () { 
if ({{form field}} == '' || {{form field}} == null ) { 
return false; 
} else { 
return true; 
}
}

Return the clicked element index (position)

Use case: You have a list of list (slider or a link block) and want to track which link was clicked – not just the link, but it’s position in the list.
Custom JavaScript Variable:

function () {
var container = document.getElementById("slider");
if (container != null) {
 var slides=container.getElementsByTagName("a");
 for (i = 0; i < slides.length; i++ ) {
   if (slides[i]=={{Click URL}}) return i+1;
 }
}
return '(not set)';
}

You can also select an element by class if the block has no id. In this case use document.getElementsByClassName(“”) and since this will return an array of elements, use container[0] to get the content.

If the slider or link block has some links before the slides, for example navigation, you can modify the code and subtract the number of links before the actual slider from index to have numeration from 1. In this example I’m adding 1 to have numeration from 1, not 0.

Search for a specific text on the page

Use case: Trigger a Tag only if there is a specific text present on the page. Return true is present or false if not.
Custom JavaScript Variable:

function () {
var content = document.body.innerText;
var query="Search Query";
if (content.search(query) > -1 ) {
 return true;
} else {
 return false;
}
}

Other examples and reading materials:

Any Custom JavaScript Variables you are using a lot? Please share in the comments below.

ShareShare on Facebook7Tweet about this on TwitterShare on LinkedIn2Share on Google+4Buffer this page

30 thoughts on “Google Tag Manager Custom JavaScript Variable examples

  1. “Check if value is not empty” can be simplified to:

    function () {
    return {{form field}} == ” || {{form field}} == null;
    }

    or even

    function () {
    return !({{form field}} &} !== ”);
    }

    Also: “Search for a specific text on the page”
    If a page is very long (e.g. in news sites), will this script cause the browser to lag in performance?

    1. Thanks for the comment! Cool, like the simplified version. If you are ok with it, will mention this as a second option.

      As for the second question – did not perform any speed benchmarks, for a standard size page it worked ok. Personally, if possible, I would not use the whole document, but select specific element (div or paragraph) where the desired text could appear.

  2. Hi Aleksandrs,

    I´m trying to run the clicked element index but I have a big problem, the slides contain identical URL in two buttons, Is there some option to solve this issue?

    thanks for this excellent post

    1. Hi! Do the links have different attributes – classes, id or other? Or one more idea – if there are different images for the links, you can make a list of images (img), instead of links (a) as in example, use Click Trigger (All Elements instead of Links), that will return image element. So you can match current image clicked with the list of images in the slider. Let me know is this doesn’t help.

  3. Hi aleksandrs,

    thanks for answering, the links doesn´t have different attributes…. :(

    Change img instead of a and returns (not set)

    function () {
    var container = document.getElementById(“myClass”);
    if (container != null) {
    var slides=container.getElementsByTagName(“a”);
    for (i = 0; i < slides.length; i++ ) {
    if (slides[i]=={{Click URL}}) return i+1;
    }
    }
    return '(not set)';
    }

    The problem I think, it is because img is not the lowest level elemnt i am clicking, It is in a div above the elemnt that has the button styles. In other words, the only action permited in whole slide is to click within button.

    thanks

    1. Hi, try this. The first selector is based on ID, so if you have only class attribute, use getElementByClass. Also later you also need to select images – getElementsByTagName(“img”) not links and match by image src.

      function () {
      var container = document.getElementById(“SliderID”);
      if (container != null) {
      var slides=container.getElementsByTagName(“img”);
      for (i = 0; i < slides.length; i++ ) { if (slides[i].src=={{Click URL}}) return i+1; } } return '(not set)'; }

  4. Hi,

    it does not work, it returns (not set), the problem is that {{Click URL}} returns only two hrefs and i have 3 buttons to track. with slides[i].src=={{Click URL}} the problem persists because i can´t gather a unique value in each button.

    In the end, i will try to contact with the software developer to insert an ID in the button.

    Thanks for your time aleksandrs

    1. Hi,

      You can take url path (Page or Link URL) and use the example from “Parse a string and return a specific element”
      function () {
      var value={{url path}}.split(“/”);
      return value[1];
      }

      If the url path is /folder1/folder2/index.html, folder1 will be the element with an index 1 (0 – before the first /, 1 – folder1, 2 – folder2 etc.)

        1. Hi,

          Updated the post above, as get many such questions :) Split the string by / string.split(“/”) and after you can either reverse the array and take the first value value.reverse()[0] or take the last element value[value.length-1]. Hope that helps!

  5. Hi Aleksandrs,

    thank you for your blog. The “search for text” is exactly what I’m looking for.
    But so far, it didn’t work for me. I want to search for the text “Thank you” after submission of a formula (the other options didn’t work with it)

    Can you give me a hint to my mistake?
    I set upthe trigger in gtm like this: JS Variable – equals – true

    My JS Variable code looks like this right now:
    function () {
    var content = document.body.innerText;
    var query=”Thank you”;
    if (content.search(query) > -1 ) {
    return true;
    } else {
    return false;
    }
    }

    Is that ok?
    Thanks a lot in advance!
    Chris
    (sorry for the double post, first time it seemed to not post it.)

  6. Hi,

    no, it just delivers a message that appeaers below the form. It is necessary to have a confirmation page that reloads?

    1. Variables get renewed on each event so since there are no events noticed by GTM – you have the last “incorrect” value. For such case, I would suggest to contact developers and add dataLayer.push() call with custom event.

  7. Hi,
    I try to fire a tag every time the price change – depending on the answers from the customers (click), the price automatically changed – we want to know in GA how many time the price changed.

    I have created 3 variables:

    PriceNew = Data Layer Variable = ecommerce.impressions.0.price –> works perfectly – this variable takes the current price displayed

    PriceIni =???

    PriceBoolean = custom Javascript:
    function() {
    if ({{PriceNew}}!={{PriceIni}})
    {return true;}
    else {return false; }
    }
    }
    My issue is I don’t know how to store the previous value of my datalayer into PriceIni.

    After it will be easy, I can create a Triggers event gtm.click only if PriceBoolean = true.

    Any ideas?

    1. Hi,

      The first thing that I can think of is using cookies to save the initial price and match new price to cookie price.
      Did not test the code, but could be smth. like this.

      {{price cookie}} – 1st party cookie variable
      {{price new}} – ecommerce.impressions.0.price
      {{price change}}
      function () {
      if ({{price cookie}}==’undefined’) {
      document.cookie=”price=”+{{price new}};
      return false;
      } else if ({{price cookie}}!={{price new}}) {
      return true;
      } else {
      return false;
      }

      You can also try Web Storage API (see the post by Simo Avaha)

      Let me know on your results, maybe will have more ideas.

      Aleksandrs

  8. Hi,

    I am using a Custom JavaScript variable and trying to test if a form textfield is empty or not, if its is empty then set my trigger not to fire a form submission event.

    I tried like the example below, but i am getting an error while i publish:
    ” Invalid HTML, CSS, or JavaScript found in template ”

    Here is the Custom JS variable code that i used:

    function () {
    var tst= document.getElementById(“edit-nom-passager-adulte-1″).value;
    if (tst !==” || tst !== null) {
    return true;
    } else {
    return false;
    }
    }

    Any help or suggestions please? Thank you

    1. Hi,

      It looks like a problem with quotes. Check that all have pairs and look the same.
      function () {
      var tst= document.getElementById("edit-nom-passager-adulte-1").value;
      if (tst !=="" || tst !== null) {
      return true;
      } else {
      return false;
      }
      }

      1. Sorry but the missing quote was just a typing error, my code is the same like you wrote. Still have that error in my Custom JavaScript variable.

        1. hm.. Copied my example into GTM and all was fine. Try to write and publish the code from the start, line by line (first only document.getElement line – publish, then add if – publish) to see where exactly is the problem.

  9. Hi Alek,
    I am looking for variable in GTM that would tell me:

    – orientation of any device (portrait or landscape)
    – internet user ‘s userAgent (ex:Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0)

    Have you any idea of some Custom JavaScript variables that works in GTM?
    Thank you

  10. Hi,

    How can we add custom dimensions for and IP address? Can’t find any scripts for this.

    I have only found this:

    But GTM is not accepting this script. It is saying to have return value. Can you please guide?

  11. Hello, i have code something like this:

    <a href=”http://www.domain.com” rel=”nofollow” > blablabla </a>

    and i want to get the gtm-class attribute value (item-1)

    what custom javascript should i use?

    1. Hi,

      I guess some attributes in your example were stripped by WordPress. If it’s a standard class attribute, use built-in {{Click Classes}}. If it’s a custom attribute named “gtm-class” try “Auto-Event Variable” with “Element Attribute” type and attribute name you want to return on a link click.

Leave a Reply

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