Google Event Tracking With jQuery

by: Preston Schmidt

jQuery Event Tracking Code

Tracking Google Events with javascript makes it easy to keep track of the events on your site that are important to you. You can have multiple events tracking all from one file, no longer needing to add markup to each instance of a link or element on your site pages to see how your users are interacting with your data.

Locate elements on your site by classes or id's and use custom variables to add more accurate information to the events as they are tracked in Google Analytics.

Here is what the javascript looks like:

$(document).ready(function() {
    //Note to remember what this is for
    $('#element').click(function() {
        ga('send', 'event', 'button', 'click', 'label');
    });
});

That's it, just like the markup you would put inside a link written in html, this is just applied with a behavioral approach. Remember to include jQuery in your document

But let's say you have the same element on multiple pages and you want to distinguish which page your users are interacting with your content, it would be nice to know what URL they are on when the event is collected in Google Analytics. So let's add a custom variable

$(document).ready(function() {
    var pathName = window.location.pathname;
	//Note to remember what this is for
	$('#element').click(function() {
		ga('send', 'event',  'Category', 'Action', pathName);
	});
});

Now we have added the current page URL to the "Label" section of the event tracking code, awesome! "window.location.pathname" grabs the current page URL, and with some handy use of concatenation, we can create a variable named pathName and use it in our event code.

Another useful variable would be to get the text of the link the user is clicking on, this way if you have a bunch of links in the same category you can use the link text to distinguish each one from the others...

$('#element').click(function() {
	var linkText = $(this).text();
	ga('send', 'event',  'Home Top Menu', linkText, 'Clicked');
});

So there we created a variable named linkText to grab the text of the link, just make sure you place it inside the click function and use $(this) or you'll grab all the links on the page that have the class or ID your targeting.

Another useful piece to collect to distinguish what page your users are on when interacting with a link is grabbing the title tag...

var pageTitle = $('h1').text();

That grabs the h1 of the current page.

So all together we could make something like this:

$(document).ready(function() {
    var pathName = window.location.pathname;
    var pageTitle = $('h1').text();
	//Note to remember what this is for
	$('#element').click(function() {
        var linkText = $(this).text();
		ga('send', 'event',  'pageTitle', 'linkText', pathName);
	});
});

Just copy and paste the click function for any element you would like to track :)

Outlier

Video, Web, and Design Agency