google-tag-managergoogle-datalayer

Google Tag Manager - collect data attributes without using the datalayer


I'm trying to collect the value of data attributes when clicking on the element containing it but I would like to do it without using the datalayer.

I'm currently using the datalayer by pushing the data attribute into the datalayer with javascript, everything works but it's annoying to always modify the code, I'd like to do the same without using javascript.

My code looks like this:

<a href="<mylink>" class="link_class" data-shop="aaa" data-product="bbb">link label</a>

In Google Tag Manager, I have created an "automatic event variable" (not sure it is called like this in English, my GTM is in French) using the name "Generic_Dataset_product" where I select "element attribute" and as an attribute, I have tried multiple things without success like data-product, gtm.data-product, product, ...

To use this variable I have created a simple trigger that detects clicks on class "link_class" and associated an event (event_category, event_action, event_label) where I add the collected variables with the right name {{Generic_Dataset_product}}. Instead of seeing the expected value, I see "track_event".

Is there a way to collect data this way? I want to use the "automatic event variables" to collect content from src, data attributes, and other elements in the code as there are no predefined variables for this in GTM.

Thanks


Solution

  • There is no reason to avoid the datalayer. The datalayer already contains the clicked element, and the data attributes are properties of that element, so you can address them via dot notation like this:

    datalayer variable for data attribute

    This saves you custom javascript (which is something you might want to avoid if you ever plan to implement a proper content security policy, since custom scripts require the use of eval).