Skip to content

Instantly share code, notes, and snippets.

@linkdigitaluk
Last active March 15, 2020 22:55
Show Gist options
  • Save linkdigitaluk/46972bc83d98ef0097ac8b447cbe5702 to your computer and use it in GitHub Desktop.
Save linkdigitaluk/46972bc83d98ef0097ac8b447cbe5702 to your computer and use it in GitHub Desktop.
[Fire Google Analytics Event] Code to fire an event in Google Analytics on click #google #analytics #jquery
/*
Google Analytics is required for the below to function
This code is ideally fired on anchor click.
It then passes the anchor link as well as a desired data-attribute on the anchor as the event label.
This has been tested with the gtag.js analytics code.
*/
function fireGoogleEvent(event) {
url = $(this).attr('href');
data = $(this).data('ATTRIBUTE');
gtag('event', 'click', {
'event_category': 'DESIRED CATEGORY NAME',
'event_label': data + ' | ' + url,
'transport_type': 'beacon',
});
}
$(/*ANCHOR ELEMENT*/).on('click', fireGoogleEvent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment