Category: Google Tag Manager

Moving away from onclick events, data attributes it is

Last updated on May 23rd, 2018 at 07:04 pm

Onclick attributes are amazing to easily sent some data to the dataLayer. It will make sure that on every click the data is being sent, let’s for example look at this:

<a href=”http://example.com” onclick=”dataLayer.push({‘eventCategory’:’Click’, ‘eventAction’:’This Link’, ’eventLabel’:’Anchor Text’});”>Link</a>

Looks valid right? It is and it will work for you. But the problem is that with external links the dataLayer push won’t hit the browser + Google Tag Manager before the browser moves on to the external link (not taken into account links that open in a new tab/window). Which means that you’ll lose the onclick event in Google Tag Manager and won’t be able to record it.

But there is a great alternative, which we switched to for The Next Web when we found out this was happening. Data attributes can be very useful instead. If you’d use them like this:

<a href=”http://example.com” data-eventCategory:’Click’, data-eventAction:’This Link’, data-eventLabel:’Anchor Text’”>Link</a>

Why this works? The link attributes on click will always be sent automatically to Google Tag Manager. So making sure that the data attributes are part of the link and not in a separate dataLayer.push will improve it.

How about React/Angular? With these platforms there is obviously never an actual refresh of the page happening and most likely you can still send a dataLayer push when you’re updating the state of the application. That’s why in most cases you won’t have to go with the technique described in this blog post. Lucky you!

Google Tag Manager

Next step is to create a variable in Google Tag Manager for all three attributes:

Make sure to set the default value to undefined. In this case Google Tag Manager won’t take any actions in the next step if there is no data, which will be defining the Trigger. Repeat this two more times for the Event Action and Event Label variables that we need to use in our Tag.

This trigger will check all incoming links, with a data-event-category attribute that doesn’t equal undefined and that has any values. In the next step for your Tag you can use all three variables that you’ve defined before.

You’re all set! You can now use data-attributes for your links to make sure that you won’t lose any data when the browser isn’t ready to receive dataLayer pushes and you just made your tracking a bit more efficient!