Google Analytics Events on Links and Form Submit Buttons

I’ve started using Google’s Universal Analytics on my websites but found (using Fiddler) that events weren’t always triggering on links and form submits.
I initially setup events on these elements so I could track how successfully they were being used across the site, however I found that the page would sometimes be so fast that it would move the user on before Google Analytics could successfully complete the event request.

Initially I thought I would just set a timeout of a couple of seconds to allow for the event request to work, but this wasn’t a great solution.
Eventually I found a callback method, hitcallback, that would allow the event to be triggered before performing the page action. (Source)

$('#linkId').click(function (e) {
	e.preventDefault();
 
	var link = this;
	ga('send', 'event', {
		'eventCategory': 'Cetegory',
		'eventAction': 'Action',
		'eventLabel': 'Label',
		'hitCallback': function () {
			document.location = $(link).attr('href');
		}
	});
});

On the links we prevent the default, trigger the event, then once we know the event request has completed the callback will perform the default action by sending the user to the link location.

The same can be done with form submit buttons. (Source)

$('#btnSubmitId').click(function (e) {
	e.preventDefault();
 
	var btnSubmit = this;
	ga('send', 'event', {
		'eventCategory': 'Category',
		'eventAction': 'Action',
		'eventLabel': 'Label',
		'hitCallback': function () {
			$(btnSubmit).parents('form').first().submit(); // Submit underlying form
		}
	});
});

Here we can see that the default action on the button is prevented, the event is triggered, then the callback performs the submit once the event request has completed.
Note: Ensure your submit button doesn’t have an id or name ‘submit’

Now we’ve ensured that all the events fire appropriately, and we’re getting the correct statistics in our reports.