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 data layer content
To trigger a data layer, a wildcard [*] can be used. This wildcard will iterate over items in array until it finds the key. In this example, the form appears if the in the data layer a key is ‘products’ and this contains the value ‘shoes’.
dataLayer[*].["products"] contains shoes
The values you set in 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 datalayers with events in SPA’s.
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.