Vishwanatha Jois
Vishwanatha Jois

Reputation: 33

How to use Custom Variable in GTM

I'm working to trigger Google Analytics using GTM only if page contains specific image name. For which I used User-Defined Variable as mll_banner and used custom javascript in it. And my custom javascript is as below.


function () {
        var mllBanner = document.querySelectorAll('[class="p-panel p-p-b-lg position-left-top style-repeatx"]')[0].style.backgroundImage;
        if (mllBanner === "url(\"/clientimg/schneider-electric/LOResource/a23d051e-55ca-4b40-88a7-90c8768e167d_coverImage.png\")") {
          alert("Return is True");  
          return true;            
        }
        else {
          alert("Return is False");
          return false;
        }
    }

If I run the above code as general JS with proper JS function name it works on browser console and return true as value. Where as I'm trying to use it in GTM and want to verify it for trigger I used like below,

Trigger

My trigger configuration

And this is neither triggering for true nor for false but if I make it like doesn't equal to then it triggers for both.

Can anyone please help how to use Javascript for User-Defined Variables in GTM and use that Variable for trigger? Thank you in advance!

Upvotes: 0

Views: 718

Answers (1)

Eike Pierstorff
Eike Pierstorff

Reputation: 32780

If you use this variable on page view it will be neither true, nor false, but undefined. That's because you try to access a property of a DOM element before the DOM is rendered (which means your queryselector will return null, and null does not have a style property).

I have to admit that is an educated guess and assumes a standard GTM installation (i.e. the snippet in the head of the page), but then you can just go into preview mode and inspect the value of the variable at the window loaded event.

I would also recommend that you do not use the queryselector, but GTM's built-in DOM variable type, because that way you can debug the DOM element independently from the rest of your function.

Also, lose the alert calls inside GTM.

Upvotes: 1

Related Questions