Home > Software design >  Detect DOM changes in Google Tag Manager Click trigger
Detect DOM changes in Google Tag Manager Click trigger

Time:08-16

Click - Just Links triggers in Google Tag Manager (GTM) don't fire on links that are added to the DOM after the page load (with a jQuery $.post).

How can I tell GTM Click to observe DOM changes like it happens with the User Engagement - Element Visibility trigger ?

Configuration options for: Just Links

Configuration options for: Element Visibility

The following configuration works perfectly for links that are already loaded in the DOM at the page load but not for the links that are added via jQuery.

Google Tag Manager tags are present (in the header and in the body).

The event is set up as follows:

_

Configuration Tag

Google Analytics GA4

Event Name

download_link_click

Event Parameters

Parameter Name Value
link_url ❴❴Click URL❵❵
link_classes ❴❴Click Classes❵❵
link_id ❴❴Click ID❵❵

Tag firing options

Unlimited

_

Trigger Configuration

Trigger Type

Click - Just Links

This trigger fires on

Click Classes contains download

CodePudding user response:

It'd be a bit expensive to observe all the DOM and constantly do some sort of differential between the elements it's watching and not, especially on some of the heavier SPAs out there.

Rather, since it sounds as though you're in control of how your jQuery script is adding these links, I would instead suggest that you augment them those links to include an onm ousedown event that pushes a new event to the GTM data layer and supplements it with the information you're wanting to capture.

For example:

$(".mySpecialDiv")
  .append('<a href="#" onm ousedown="(function() {dataLayer.push({'event': 'click_mySpecialLink1', 'exitUrl': '#'"});)()">Click me!</a>');

When the user clicks down on the link (e.g. not waiting for a full click), you populate the GTM data layer with a new object that identifies itself with a named event and some additional information. While it'd be expensive for GTM to monitor every DOM element, it's relatively cheap for it to monitor dataLayer.

In GTM:

  • Set up a variable mapped to various properties you're pushing in
  • Set up a new trigger that's based on the event name you're using
  • Set up the tag that's responsive to the click and bind to your new trigger
  • Related