Shoora
7/1/2015 - 8:32 PM

GA Event Tracking function that uses a link class and data attributes

GA Event Tracking function that uses a link class and data attributes

$('.event-track').on('click', function(){	
	var eventCategory = $(this).data('event-category');
	var eventAction = $(this).data('event-action');
	if ($(this).data('event-label') != undefined) {
		var eventLabel = $(this).data('event-label');
	}else{
		var eventLabel = $(this).html();
	}
	if (typeof ga !== 'undefined') {
		// console.log("Universal Analytics: " + eventLabel);
		ga('send', 'event', eventCategory, eventAction, eventLabel);
	}else{
		// console.log("GAQ Style: " + eventLabel);
		_gaq.push(['_trackEvent', eventCategory, eventAction, eventLabel]);
	}
});

// HTML
<a class="event-track" data-event-category="Category Text Here" data-event-action="Action Text Here" data-event-label="Label Text Here" href="http://www.google.com" target="_blank">Link Text</a>
// When data-label is not present it will use the HTML of the tag "Link Text"
<a class="event-track" data-event-category="Category Text Here" data-event-action="Action Text Here" href="http://www.google.com" target="_blank">Link Text</a>