0
votes

I have been able to capture and push URL's with the Google Tag Manager default, but I have been having trouble trying to push custom data layer attributes.

For example:

Before the GTM script loads I push the current page url into the dataLayer.

<script>
 var currentPage = (document.URL);
 dataLayer = [{
  'pageURL': currentPage
 }];
</script>

And then on various elements I'm pushing content to the dataLayer when they are clicked:

<a id="tracking-image" href="#" onclick="dataLayer.push({'#elementID': 'tracking-image'});"></a>

I've been having trouble capturing these in GTM / Google Analytics. Ultimately I would want in captured in Google Analytics like so:

Label: currentPage

Action: tracking-image

But currently it's just tracking the gtm.js event firing multiple times.

1

1 Answers

0
votes

You do not need to push the element id to the datalayer (GTM can read the id by itself). What you are missing is an event to trigger your tag.

"Events" in GTM are not related to event tracking in Analytics and only vaguely related to native Javascript events. "event" is a reserved macro name, and it's purpose is to trigger tags; there are some pre-defined events on page load start (gtm.js) , page load finish (gtm.dom) etc.

If you want to trigger a tag that does not fire on page load chances are that you need a custom event.

One way would be to change your code like this:

<a id="tracking-image" href="#" onclick="dataLayer.push({'event': 'imagetracker'});"></a>

Then you could set up a rule with the condition "{{event}} equals imagetracker" which you fire your tag.

Probably a better way would be to use GTMs event listener tags. There is a link click event listener tag and a generic click listener tags. Since your link target is not a valid url I would choose the generic click listener. So you'd set up a new tag of the type click listener and have it fire on all pages. Now if an element is clicked the event macro will be assigned the value of GTM click.

Event listeners will also automaticall fill auto-event variables that hold various properties of the clicked element. This would allow you to access the clicked elements id though a macro called, somewhat unsurprisingly, "element id".

So you would create a rule where "{{event}} equals gtmClick" AND "{{element id}} equals imagetracker". That would fire a tag if the link is clicked.

Caveat is that GTMs event listener tags fail when there is already a click event on the element that returns "false" to suppress standard behaviour. Infos and workaround are and workaround on Simo Ahavas Blog (which is pretty much the go-to place for all things GTM-related).