Search code examples
javascriptgoogle-tag-manager

JS click event handlers and GTM


I'm trying to get something working in GTM but I probably misunderstood the inner workings. Here's what I try to do.

I have a tag that is loaded on the relevant page:

<script>

  document.querySelector('#btnNext').addEventListener('click', {{EPT - Handler}}, false);
  document.querySelector('#btnPrev').addEventListener('click', {{EPT - Handler}}, false);
  
</script>

and I have defined the {{EPT - Handler}} as a Variable of type custom javascript as follows:

function() {
    return function (event) {
        console.log('EVH ', event);
    }
}

This works the first time I click on one of the buttons. If I look into the attached events before the click, I see that there are three events attached, among them, the above handler. Then I click, the console.log() is executed and all seems well. But when I now look at the handlers, there are only 2 of them and the one above is missing. Of course now when I click, the above handler isn't called anymore.

What am I missing here?

The bigger picture Currently I have a number of Tags that send events to GA depending on what was clicked inside an SPA. Each Tag has its own Trigger.

I thought I'd just wire up all the buttons with one event handler instead and have that event handler put the stuff that should go to GA into the dataLayer where it finally gets sent as result of the customEvent I put in the dataLayer. I'd have a much smaller number of tags and triggers (1 tag, 1 trigger) so I have a simpler setup than currently.

Now, after explaining all of this, I'm pretty sure I don't need this custom JS event listener at all :)

Still I would be interested in who deletes my event listener...

Thanks in advance


Solution

  • Since I cannot see your actual page, I make an educated guess. Probably your next/previous buttons update a part of your page via some sort of Ajax call. If they are themselves replaced with updated content, the event handler is lost.

    The click handlers in Google Tag Manager works around such problems by not attaching events to the element directly. Instead handlers are attached to the document directly. If a link is clicked the event bubbles up to the document. The handler attached to the document inspects the original event target, and if it meets the configured conditions they fire the respective triggers. This approach also works on dynamically inserted/replaced elements.

    A bit of guesswork as I don't see your page, but at least a theory you can check.