GTM Trick: Tracking Clicks on Links without CSS Selectors
GTM Trick: Tracking Clicks on Links without CSS Selectors

GTM Trick: Tracking Clicks on Links without CSS Selectors

Disclaimer: Always use (if possible) DataLayer for sending user interaction information to Google Analytics via GTM.

Tracking clicks on any element using GTM is quite straight forward. If the site is awesome like my site: 

GTM Trick: Tracking Clicks on Links without CSS Selectors

Each link has a CSS Class and it is quite easy using GTM to track any clicks on such links. 

GTM Trick: Tracking Clicks on Links without CSS Selectors

But tracking can difficult if the “a” element does not have a CSS Selector. For Example: the navigation links for this site does not have any CSS Selector attached to it. 

GTM Trick: Tracking Clicks on Links without CSS Selectors

This causes the following problem: 

GTM Trick: Tracking Clicks on Links without CSS Selectors

But we can easily resolve is issue by creating Custom Code variable.

As we can see that this element inherits it’s look and feel from the immediate parent element. We can use the “closest()” JavaScript method to find this information.

MDN Reference: Element.closest()

Step by Step solution:

1. Create a Custom Code Variable in GTM

2. Use the following code to get the Class or ID of the parent element

function() {
  'use strict';
  try {
    var clickEvent = {{Click Element}};
    var clickSelector = clickEvent.closest('.menu-item').getAttribute("id");
    return clickSelector;
  } catch (err) {
    console.log(err);
  }
}
}
GTM Trick: Tracking Clicks on Links without CSS Selectors

3. Verify in “GTM Preview Mode” 

GTM Trick: Tracking Clicks on Links without CSS Selectors

4. Create “Click – All Elements” Trigger and use this variable as the firing condition

GTM Trick: Tracking Clicks on Links without CSS Selectors

5. Now we can track the link clicks using this Trigger.

GTM Trick: Tracking Clicks on Links without CSS Selectors

Hopefully, this post will serve as a useful guide for click tracking using to Google Tag Manager.


要查看或添加评论,请登录

社区洞察