Tracking Multiple Google Analytics Events Dynamically… Like a Boss!

Tracking events can be a bit daunting. If you have to track every event on a page, you could be writing a ton of code to control each event. Well, I have a solution for you! I wrote a small simple script that is 4 lines long. This script will go through all your events, and fire when clicked. All you have to do is place your Category, Action, Label, and Value to each element, and the script will do the rest. Below is the script I created.

$(document).on('click', '[data-event]', function(){
	var data =  $(this).data('event');
	ga('send', 'event', data.category, data.action, data.label, data.value);
});

Once you have that script on the page, all you have to do is label each element with the following attribute:

data-event='{"category":"Your Category","action":"Your Action","label":"Your Label","value":"Your value"}'

The script will send Google Analytics the information categories on this data-event attribute that are not blank.

For example, a link, would look like this:

View Hire Me Page!

<a href="/hire-me/" data-event='{"category":"Your Category","action":"Your Action","label":"Your Label","value":"Your value"}'>View Hire Me Page!</a>

Happy event tracking!!

Leave a comment

Your email address will not be published. Required fields are marked *