Laurent
Laurent

Reputation: 1563

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

Upvotes: 3

Views: 8526

Answers (2)

BNazaruk
BNazaruk

Reputation: 8126

Getting arbitrary attributes of clicked elements in GTM is a trivial task. And there are many ways of doing it. I prefer CJS cuz I often need to do mutations and sanitizing there. Your problem is that you're not debugging it properly.

First, make a trivial CJS variable like so:

function(){
  return {{Click Element}}.getAttribute("data-shop");
}

Now open your preview debugger and actually go inspect all variables GTM sets on your click. Including your new CJS var as well as your auto-event vars. If you don't find what you're looking for from there, come back here and show us screenshots from the actual debugger and let's debug from there.

Here's how you enable {{Click Element}}: enter image description here

Upvotes: 4

Eike Pierstorff
Eike Pierstorff

Reputation: 32780

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).

Upvotes: 2

Related Questions