Ali Jafarian

The Web Project

I'm building a new online platform for learning web design and development. Check out the KickStarter to get early access and heavily discounted rates!

View the KickStarter


Have you ever wanted to track user clicks on your website or web app? Great – then you’ve come to the right place! Today I’m going to show you how to track click events using JavaScript and keen.io.

For starters, let’s talk about keen.io. Keen is a new platform for developers to build custom analytics. You can learn more on keen’s website. I choose to use keen for several of my projects because sometimes Google Analytics is just too much… and, as a developer I like the idea of writing my own analytics tracking to pull in specific data for custom dashboards.

Step 1 – Create a keen account

First, let’s head on over to keen.io and create an account. Accounts are free up until 50,000 data points – woohoo!

After creating an account you’ll also need to create a project – just name it something easy like your website. Then you’ll get a project id and some API keys we’ll need for the next steps.

  • project id
  • write key (used for pushing data to keen)
  • read key (used for pulling data from keen)

Step 2 – Add keen to your site

There are a few ways to include the keen library to your site, but the easiest way is probably via CDN like most JavaScript libraries. Include this somewhere on your site where you can track all pages (ex: header or footer). For my WordPress sites I like to include this in the header.php so I ensure it gets loaded before any custom footer scripts I include in pages.

<script type="text/javascript" src="https://d26b395fwzu5fz.cloudfront.net/3.2.6/keen.min.js"></script>

Step 3 – Create the Tracking Script

Now we’re going to create some JavaScript to track specific clicks. The code below references the keen JavaScript SDK with some additional jQuery I added for custom event names.

First, we’ll add the keen client object with our API keys – this allows you to communicate with keen.

// Configure keen instance
var keenClient = new Keen({
    projectId: "your-project-id",
    writeKey: "your-write-key"
});

Next, we’ll create an object and function for the keen events. Note the extra addons we’re using to pass additional information on IP address and user agent. These helpful add-ons can be found in keen’s API docs.

// Object for tracking page views
var keenPageView = {
    referrer: {
        url: document.referrer
    },
    page: {
      	url: document.URL,
      	title: document.title
  	},
  	ip_address: "${keen.ip}",
  	user_agent: "${keen.user_agent}",
  	keen: {
      	addons: [
      	  	{  
	          	name: "keen:referrer_parser",
	          	input: {
	              	referrer_url: "referrer.url",
	              	page_url: "page.url"
	          	},
	          	output: "referrer.info"
	      	},
	      	{
	          	name: "keen:ip_to_geo",
	          	input: {
	              	ip: "ip_address"
	          	},
	          	output: "ip_geo_info"
	      	},
	      	{
	      	  	name: "keen:ua_parser",
	          	input: {
	          	  	ua_string: "user_agent"
	          	},
	          	output: "parsed_user_agent"
	      	}
      	]
  	}
};
// Function for sending pageviews event
keenClient.addEvent("pageviews", keenPageView, function(err, response) {
	if (err) {
		console.log("keen pageviews tracking error");
	} else {
		return
	}
});

Lastly, we’ll create a jQuery click event to pass the needed data to the function.

// ----- CLICKING ----- //
// Object for tracking clicks
var keenClick = {
	url: document.URL,
	ip_address: "${keen.ip}",
	user_agent: "${keen.user_agent}",
	keen: {
	    addons: [
	        {
	            name: "keen:ip_to_geo",
	            input: {
	                ip: "ip_address"
	            },
	            output: "ip_geo_info"
	        },
	        {
	        	name: "keen:ua_parser",
	        	input: {
	          		ua_string: "user_agent"
	        	},
	        	output: "parsed_user_agent"
	        }
	    ]
	}
};
// click tracking via jQuery
// requires adding "keen-click-track" class to DOM element
$('.keen-click-track').on('click', function(){
	var clickName = $(this).attr("data-keen-name");
	keenClient.addEvent(clickName, keenClick, function(err, response) {
		if (err) {
			console.log("keen click tracking error");
		} else {
			return
		}
	});
});

Full Code Example

We’re basically sending dynamic event names based on a data-keen-name attribute instead of naming each event with it’s own function (which is what the keen example demonstrates). The full code example for your tracking script is below.

<script type="text/javascript">
	// Configure keen instance
	var keenClient = new Keen({
	    projectId: "your-project-id",
	    writeKey: "your-write-key"
	});
	
	// Object for tracking page views
	var keenPageView = {
	    referrer: {
	        url: document.referrer
	    },
	    page: {
	      	url: document.URL,
	      	title: document.title
	  	},
	  	ip_address: "${keen.ip}",
	  	user_agent: "${keen.user_agent}",
	  	keen: {
	      	addons: [
	      	  	{  
		          	name: "keen:referrer_parser",
		          	input: {
		              	referrer_url: "referrer.url",
		              	page_url: "page.url"
		          	},
		          	output: "referrer.info"
		      	},
		      	{
		          	name: "keen:ip_to_geo",
		          	input: {
		              	ip: "ip_address"
		          	},
		          	output: "ip_geo_info"
		      	},
		      	{
		      	  	name: "keen:ua_parser",
		          	input: {
		          	  	ua_string: "user_agent"
		          	},
		          	output: "parsed_user_agent"
		      	}
	      	]
	  	}
	};
	// Function for sending pageviews event
	keenClient.addEvent("pageviews", keenPageView, function(err, response) {
		if (err) {
			console.log("keen pageviews tracking error");
		} else {
			return
		}
	});

	// ----- CLICKING ----- //
	// Object for tracking clicks
	var keenClick = {
		url: document.URL,
		ip_address: "${keen.ip}",
		user_agent: "${keen.user_agent}",
		keen: {
		    addons: [
		        {
		            name: "keen:ip_to_geo",
		            input: {
		                ip: "ip_address"
		            },
		            output: "ip_geo_info"
		        },
		        {
		        	name: "keen:ua_parser",
		        	input: {
		          		ua_string: "user_agent"
		        	},
		        	output: "parsed_user_agent"
		        }
		    ]
		}
	};
	
	// click tracking via jQuery
	// requires adding "keen-click-track" class to DOM element
	$('.keen-click-track').on('click', function(){
		var clickName = $(this).attr("data-keen-name");
		keenClient.addEvent(clickName, keenClick, function(err, response) {
			if (err) {
				console.log("keen click tracking error");
			} else {
				return
			}
		});
	});
</script>

Step 4 – Add the CSS class to your DOM elements

Now we need to add the keen-click-track class to any elements we want to track, along with the event name. In the example below I’m sending keen an event named “click_homepage_hero_start_free_trial” to track homepage clicks to my sign-up page.

<a href="/sign-up/" class="keen-click-track" data-keen-name="click_homepage_hero_start_free_trial">Start Your Free Trial</a>

Step 5 – Verify the results in keen

The last step is to verify that you’re events are being logged to keen. Login to your account, find your project, and visit the “Overview” tab. Then select your event from the “Events” dropdown. You can now click the “Last 10 Events” tab to see your results.

screenshot_keen_js_tracking_001


Summary

That’s all there is to it – simple click tracking via JavaScript and keen.io. Now that you’re tracking clicks you can also create some cool keen.read queries to visualize the data! Lookout for a future blog post on that soon…


  • keenClick is undefined

    • Good catch, Brian! Looks like I forgot some code… should be updated now.