Rothrock
Rothrock

Reputation: 1511

Setting custom label in tag manager event

We have two links on our page and want to record clicks on them using gtm.

<a href="..." data-gtm-event="register">Register now</a>
<a href="..." data-gtm-event="logon">Log on</a>

We have a trigger for clicks on elements that match the css selector of [data-gtm-event].

And finally we have a tag set with uses the trigger to record a Link event. The trigger is firing and the tag is working.

But I would like to have a way to change the label on the recorded event to be either Register or Log on depending upon which link they clicked. In the past we made one trigger for each and one tag for each, but that isn't sustainable.

I know I can create custom javascript variable such as this:

function(){
   return "My label";
}

And then use that custom variable to assign the event label. And I do see that working.

Is there a way to make that dynamic?

I've found examples on the web for using the dataLayer but I don't want to add onclick attributes to my html elements.

Is there a way in the javascript variable to access the clicked element and get the value from its data- attributes?

I've found pages on using Macros, but that is the old version, right?

Upvotes: 0

Views: 2409

Answers (1)

Eike Pierstorff
Eike Pierstorff

Reputation: 32770

Sure. If you enable the built-in "Click" variables one of them is "Click Element", which actually returns the DOM element with all it's attributes.

So in your custom javascript variable you can reference this and do

function() {
  return {{Click Element}}.getAttribute('data-gtm-event');
}

(maybe you want to check if the attribute actually exists first).

Upvotes: 2

Related Questions