One of the greatest joys of GTM is being able to capture difficult or hard to track interactions on diverse sites ranging from WordPress to Magento. Oftentimes out of the box GTM does not capture important data like ‘element class’ or ‘click id’. These variables can be used to create firing rules with laser precision but without them tracking can be near impossible.

One of the best ways to capture information on a page that is not readily available is with a custom javascript variable. All it takes is a simple javascript code and a bit of CSS. If you are new to CSS check out our CSS guide here.

To setup custom JavaScript variables in Google Tag Manager (GTM), follow these steps:

Sign in to GTM and navigate to the Variables tab.

Click the “New” button to create a new variable.

Select the “Custom JavaScript” variable type.

In the “Custom JavaScript” field, enter the JavaScript code that you want to use for your variable. This code should return a value that you want to use in your tags or triggers.

Give your variable a descriptive name and save it.

You can now use this custom JavaScript variable in your tags and triggers by selecting it from the list of available variables.

For example, to create a custom JavaScript variable that returns the value of a specific element on the page, you could use the following code:

function() {

  return document.getElementById('my-element').value;

}

Copy code

This code will return the value of the element with the ID “my-element”. You can use this variable in your tags or triggers by selecting it from the list of available variables.

Using Custom Variables as a Trigger

Navigate to your desired tag and click on “Add Trigger”

This can be a range of different type btw

In this instance we will look at a link click trigger

The link click trigger will have 2 options, select the bullet that says “Some Link Clicks”

Now select a variable from the drop down – you should see your newly created custom variable as an option.

Give this variable a condition for which you would like it to fire in this case we used a specific value for the custom variable we had created early in the page

Save and preview – you will now see that your new  variable.

GA4 Parameters:

In a similar way that the custom variable’s value can be used as it a conditional, it is also highly effective as a captured parameter value within a GA4 tag. The same way your previously created custom variable shows up as a condition option you should see the name of the custom variable available as a dynamically populating attribute value

Set the condition to event

Overall, custom JavaScript variables can be a powerful tool for creating dynamic and flexible tracking configurations in GTM. By using custom JavaScript, you can create variables that return values based on specific conditions or user actions, allowing you to track data that is relevant to your business.