How do I trigger a form based on a JavaScript variable?

In this article, we explained how you can add conditions to your deployment. In the following article, we will elaborate a bit more on the JS Variable condition.

The JS variable should be globally accessible, so for instance, if user_id is a global variable it will take the value it contains and passes it along as feedback (as a string). The variable can also be an object or array or even a nested object (for instance: test_object.user_id) if the value of the specified variable is an array or object it will be encoded into a JSON string. Basically, as long as the variable's scope is global we'll be able to pick it up.

Examples

Trigger on a simple JS variable

The form appears if the variable example = "triggered":

Trigger on nested objects

If your object looks like: variable example = {'userGroup': 'admin'}, then you can use example.userGroup matches admin to make the form appear:

Trigger on data layer content

It is also possible to trigger based on values within the dataLayer. You can type dataLayer in your browser console to find out what is available.

Within the dataLayer, the syntax can vary. One way to get the correct syntax, is to copy the property path.

In the following image there are two different examples of how to reference values in the dataLayer.

To trigger based on the data layer, a wildcard [*] can be used. This wildcard will iterate over items in an array until it finds the key. This is especially useful when the item is not in a static position in the array.

In the example below, the form will trigger if the ‘products’ key exists and contains the value ‘shoes’.

dataLayer[*].products contains shoes

The values you set in the conditions are stored as a String. This has some implications if you want to check for a Boolean value in the variable on your page.

To iterate with a wildcard through the items in the array from the last item, the wildcard [*LAST] can be used. This can be useful for a dataLayer with events in SPA’s.

The * wildcard can be used recursively. E.g. dataLayer[*].basket[*].prices

JS Variable if the condition is true

Let’s say your specified variable, var1 is true. Adding the condition var1=true will not work, as “true” != true. If var1 is true (boolean), you could use the condition var1=1.

JS Variable if the condition is false

Let’s say your specified variable, var1 is false. Adding the condition var1=false will not work, as “false” != false. If var1 is false (boolean), you could use the condition var1=0.


Related articles