Im new to GTM and trying to create a custom javascript variable to return whether or not an action/event was in the footer or main body of the website. I want to use it to differentiate triggers in GTM like link clicks/form submit, etc.
Custom javascript variable code:
function() {
var e = {{Form Element}};
return e[0].indexOf("#footer");
}
On form submit shows up in the data layer as undefined:
But if I take off the .indexOf("#footer")
and try
function() {
var e = {{Form Element}};
return e[0];
}
It shows in the data layer as:
So im not sure why .indexOf()
wasn't working but then If I try and change my trigger to us contains "#footer"
logic in GTM it doesnt match.
Im probably doing multiple things wrong. But I dont even know enough about GTM to know what question to ask.
Please help.
e[0]
is not a string, but an HTMLInputElement
. The conversion to a string is only done by the UI there, and, as far as I can tell, is not anything standard.
If you want to check whether an element is contained in the subtree of another, use .contains()
:
function() {
var e = {{Form Element}};
return document.getElementById('footer').contains(e);
}
You might have to replace 'footer'
with 'footer-router'
or something like that, since I don't actually see #footer
by itself in the element's path.
I also changed e[0]
to just e
, since the first input element of a form and the form itself would be in the same subtree, even if it's the form itself that has ID footer
.