skip to Main Content

I have a web page that is dynamically generated by a script (it’s a member dashboard). I’m trying to track when someone clicks on a dropdown which changes their selection of a care provider. Unfortunately I cannot alter the source code at all, I must come up with a solution using GTM alone.

I have this code:

<script>
console.log('Hello!!');
function dropdownListen(){
  var matOption = document.querySelector("mat-select[name=providerSelect] .mat-select-value span span");
   console.log(matOption);
      var callback = function(){
        //window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
          "event": "selectionMade"
        });
      };
      
  matOption.addEventListener("change", callback);
}
window.onload = dropdownListen();
</script>

The first Hello! logs in the console, but the second logging matOption returns null. I have confirmed that the selector works using this codepen (I just copied the code I’m trying to target into the HTML) https://codepen.io/pointnine/pen/zYMZvBy?editors=1111

I think it may have to do with the code running before the page is loaded? I can’t think of anything else. I currently have the custom HTML tag in GTM triggered on window load, but I’ve tried on DOM ready and page view which also doesn’t help. Any thoughts would be appreciated!

2

Answers


  1. Yes normally it is the order issue.

    Here is a way to check if it is window load already.

    <script>
    console.log('Hello!!');
    function dropdownListen(){
      var matOption = document.querySelector("mat-select[name=providerSelect] .mat-select-value span span");
       console.log(matOption);
          var callback = function(){
            //window.dataLayer = window.dataLayer || [];
            window.dataLayer.push({
              "event": "selectionMade"
            });
          };
          
      matOption.addEventListener("change", callback);
    }
    
    // if it's already window load. Just execute the function
    if (document.readyState === 'complete') {
      dropdownListen();
    } else {
      window.onload = dropdownListen;
    }
    </script>
    
    
    Login or Signup to reply.
  2. Is there any reason why you’re not using actual functionality of GTM rather than just using it to inject custom html?

    You could deploy a click trigger in GTM that would be triggered by the click on the dropdown, then track it or do whatever you want with it. GTM doesn’t need elements to exist in DOM on its execution since it doesn’t add event listeners to them. GTM analyzes clicks upstream and checks the targets against its selectors.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search