I have created a Custom JavaScript variable in GTM to pull out the form title on a popup form.
I am using element visibility and CSS selector to identify the forms.
This is a page with multiple forms so instead of having multiple tags and triggers, I want to do it on one and it to dynamically change.
So the CJS is:
function() {
return document.querySelector ('div._form-title').innerText
}
And it works perfectly when testing in the console, but when I test it in preview mode of Google Tag Manager, the first one works fine, but then if I open any other forms, the previous value shows again in the new tag.
It's like it's unable to fetch the most recent one.
The tag is triggered on element visible and observes DOM changes, so I would have thought the CJS variable would run again for the updated value, but it doesn't.
Any ideas?
Otherwise, in the variables that do come through automatically, when the popup loads, "Click text" comes through as the entire form text.
So an alternative way to do it could be to return the click text, but to shorten it - do you know how to return e.g. just the first 25 characters of the "Click text" variable?
Thanks in advance :)
On a page with multiple forms (or multiple elements that match the selector) this will always return the first match. That is just how document.querySelector works, not something GTM specific (also do not use custom HTML to get DOM nodes, use the built-in DOM variable type - this avoids the use of eval, which is good for security and performance and allows for stricter content security policies if that is an issue for you).
If you say that using click text is a viable alternative you do not need to shorten it (you could do that in a custom Javascript variable that returns a substring of the {{Click Text}} variable, but since you do not have to type out the click text anywhere this seems unnecessary), just use the starts with condition in your trigger filter and match the first 25 characters: