How to track user behavior in real time with Google Analytics

Share:
Source Code

Today we’re going to become NSA and spy on our users. JK!  Well not really, we’re going to learn about how we can anonymously collect user behavior data with Google Analytics in REAL TIME in order to better understand how your visitors use your site.

Note: Google Analytics is the industry standard for analytics tracking on the web.  This tutorial is NOT an introduction to Google Analytics and we are going to assume you have basic knowledge of how to set it up on your site. 

How does it work?

The little known feature we’re going to look at is called Event Tracking.

Event tracking allows you to measure how users interact with the content of your website. For example, you might want to measure how many times a button was pressed, or how many times a particular item was used in a web game.

you will be able to track ANY action your users perform on the site and  consolidate them into a full analytics report.  This is very very powerful!

The API

To use the API, all you have to do is to make sure you have the GA snippet installed on your site and then in your custom JS script, invoke the api when the user performs an action, the api is a single simple function call:

ga('send', 'event', category, action, label, value);
Value Type Required Description
Category String Yes Typically the object that was interacted with (e.g. button)
Action String Yes The type of interaction (e.g. click)
Label String No Useful for categorizing events (e.g. nav buttons)
Value Number No Values must be non-negative. Useful to pass counts (e.g. 4 times)

To learn more about the API, visit here

Real world example

Let’s do a practical example from the real world.  Let say I own a restaurant site and I have a menu  full of categories of food, and I want to know which items from my menu my users like the most.

I’ll set up a simple bootstrap site and attach my GA script to the footer of the site:

  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-XXXXXXX-X', 'auto');
    ga('send', 'pageview');
  </script>

where UA-XXXXXXX-X is your Google Analytics ID.

You can get our full Index.html from our repo here

It’s a simple site for a fictional store call Penta Code Diner built with Bootstrap and jQuery.

To demonstrate the usefulness of GA Events, let’s track what our users are clicking on within our top nav menu.  In the menu we have a couple of items:

  • jQuery Soup
  • Ember Salad
  • React BBQ
  • Angular Coolaid
  • Mocha Cola
  • Bad to the Backbone

To set up GA events, let’s add some data attributes to the actual HTML elements.

For instance, jQuery Soup’s DOM element should look like this:

<li><a href="#" data-gaCategory="Menu Clicked" data-gaAction="Javascript Menu Dropdown" data-gaLabel="jQuery Soup">jQuery Soup</a></li>

we’re simply adding data attributes corresponding to each of the parameters of GA Event api.  Later on, we’ll grab those values with our javascript.

We’ll also add some data attributes to the Buy button:

<h2>Item 1 $10</h2>
<button type="button" class="btn btn-lg btn-default btn-buy" data-gaCategory="Sale" data-gaAction="Purchase Item" data-gaLabel="Item 1" data-gaValue="10">Buy Item</button>

Notice an extra data attribute call data-gaValue we’ll use this to track the actual value associated with this event, in this instance we can use it to track total sale generated from Item 1.

ok, we’re done with setting up the HTML, let’s see what our scripts.js look like:

$(function() {
	    $('a').on('click', function(e) {
		        //for our example, we'll prevent default click behavior
    		    e.preventDefault();
    		    var $e = $(e.currentTarget);

    		    var category = $e.attr('data-gaCategory');
    		    var action = $e.attr('data-gaAction');
    		    var label = $e.attr('data-gaLabel');
 
    		    console.log(category, action, label);
    		    if (category && action && label) {
        			    ga('send', 'event', category, action, label, null);
    		    }
    	});

	    //Buy item button
	    $('.btn-buy').on('click', function(e) {
        		//for our example, we'll prevent default click behavior
        		e.preventDefault();
        		var $e = $(e.currentTarget);
        		var category = $e.attr('data-gaCategory');
        		var action = $e.attr('data-gaAction');
        		var label = $e.attr('data-gaLabel');
		        var value = parseInt($e.attr('data-gaValue'), 10);

		        console.log(category, action, label, value);
		        if (category && action && label && value) {
			            ga('send', 'event', category, action, label, value);
        		}
	    });
})

If you’re familiar with jQuery, you should have no problem understanding this.  The script will look at all <a> tags and set click event listener on them, it will look at the element and finds relevant data attributes associated with it and set them as a list of variables, and if they’re all set, it will make a call to Google Analytics Event API and get the action tracked. Likewise for the Buy button’s click event.

if (category && action && label && value) {
			    ga('send', 'event', category, action, label, value);
}

We can give this a spin by starting a local server, if you have OSX, you can run:

python -m SimpleHTTPServer

within the folder and it will start a server. Head over to http://localhost:8000 and you should see this:

pentacode diner

Next you can click on something from the drop down menu in the top nav, and also click on the Buy Item button.  Then head over to GA reporting suite and go to the Real Time tab and you should see data flowing in!

googleanalyticseventstracking

Amazing right? Now you will be able to track users on your site in real time!  This is just a simple example of GA Event usage, the possibilities are limitless.  Let us know if you come up with creative uses for it in the comments below.

Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode