Sometimes you need additional information about a product/event, but you can’t get it from the HTML of the code. In this case, it is easier for developers to make an additional attribute, as a rule, it starts with the prefix data- something else.
For example, a piece of HTML code, where data-recom-type (highlighted) and data-pos-num send additional parameters for analytics.
In order for such parameters to be fixed by GTM when it clicked, you need to do the following:
- Go to Variables –> scroll to User-Defined Variables, create a Custom JavaScript variable and paste the code:
2. The code looks like this: a function is created (without it, you cannot create a Custom JavaScript variable) and inside the function, on a click event (it’s {{Click Element}}), the nearest attribute is searched for with the name data-recom-type in my case and the value of this attribute is displayed at the end.
function() {
var e = {{Click Element}};
var closestAtt = e.closest('[data-recom-type]');
return closestAtt.getAttribute("data-recom-type");
}
3. After we save the variable and insert it into the desired piece of code, in my case this is a parameter to the event in Yandex Metrica:
Such a simple solution was made based on the article: //https://mixedanalytics.com/blog/value-data-attributes-javascript-gtm/