I have a variable watchedVariable
that can either be “ABC” or “DEF” and a tag that should fire every time the value of watchedVariable
changes from “ABC” to “DEF” or vice versa.
I tried to write a javascript that pushes e.g. "event" : "watchedVariable changed"
based on an older entry I found, but I can’t apply it to my use case (my js skills are pretty basic).
I adjusted the name of {{watchedVariable}}
and the dataLayer.push command at the end. Is there more to adjust?
Would be super thankful for any help on this!
<script>
var someEventIsTriggered = function(e) {
var target = $('input#watched');
var lastEvent = dataLayer
.filter(function (e) { return e.event === 'gtm.customEvent'; })
.pop();
var lastValue = lastEvent instanceof Object
? lastEvent[{{watchedVariable}}]
: false;
// Trigger a generic "gtm.click" event on every click
dataLayer.push({
"event": "gtm.customEvent",
{{watchedVariable}}: target.val()
});
if (lastValue !== target.val()) {
dataLayer.push({
"event": "watchedVariable changed"
});
}
};
</script>```