Universal Google Analytics event tracking with vanilla JavaScript & data attributes

3 min read

I recently had to add Google Analytics event tracking on a bunch of buttons on our own experiments website Floor19. I battled to find a universal script that handled the different types of tracking in a few lines of code, so I thought I’d put the one that I came up with here.

Events

First, we need to reference how the events need to be sent to GA. This snippet is from the official documentation here.

Here is a brief explanation of each parameter in square brackets above:

  • [eventCategory] – a broad category name for the actions taking place. Examples could be ‘social links’, ‘main CTAs’, ‘internal buttons’. Basically anything that makes sense within the context of the project.
  • [eventAction] – the action the user will be taking when recording the event. eg: ‘click’, ‘copy’, ‘form submit’ and so on.
  • [eventLabel] –  I usually use this label to specifically name the action. eg “Home: Facebook Btn”, “Footer: Sitemap Btn” etc.
  • [eventValue] – This is optional (so is eventLabel btw). You only need this if you want to assign a number to the event. you don’t have to put quotes around the number.

Buttons / Elements

Now that we understand each tracking property, we can create any number of buttons, assign a class to them ‘ga-track’ for example. We then add data attributes for each GA event tracking property that we want to send. Here is an example of a button:

JavaScript

Now we need to write the JavaScript that finds all the elements that have a class of ‘ga-track’, and then when a particular event takes places (eg: a click), we send the events to Google Analytics based on the data-attributes of the element. Bear in mind this snippet is just for an “onclick” event, but you could have “oncopy”, “onsubmit” or any other JavaScript event that is available. Here is the JS:

I usually just add this JS underneath the default Google Analytics snippet. I think it’s nice to keep it all together. Here is what your new GA snippet would look like:

download

Contact


Want to work with me or the Lab19 team? Great news! Reach me using the relevant links below: