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:
Each link has a CSS Class and it is quite easy using GTM to track any clicks on such links.
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.
This causes the following problem:
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); } }
}
3. Verify in “GTM Preview Mode”
4. Create “Click – All Elements” Trigger and use this variable as the firing condition
5. Now we can track the link clicks using this Trigger.
Hopefully, this post will serve as a useful guide for click tracking using to Google Tag Manager.