• HEX: #337fa2
  • RGB: rgb(51, 127, 162)
  • HEX: #f4f4f4
  • RGB: rgb(244, 244, 244)
  • HEX: #f4a23f
  • RGB: rgb(244, 162, 63)
  • HEX: #9cb0b4
  • RGB: rgb(156, 176, 180)
  • HEX: #a07c54
  • RGB: rgb(160, 124, 84)

Bootstrap Button CTA Event Tracking with Google Analytics

Bootstrap Buttons

At XebiaLabs we use Twitter Bootstrap for out general site grid and various UI components. We make extensive use of the bootstrap buttons for everything from our subscribe buttons to dropdowns.

Something that I’ve always wanted to do as track link clicks as events using Google Analytics, but that was a little bit overkill. So, I decided to start tracking button clicks at the very least.

Every bootstrap button has the .btn class as well as two other classes to specify size and coloration. If you are using a framework like foundation you could use .button instead of .btn. In fact you could probably just paste in a bunch of standard button classes into the code below to track button clicks.

Anyways, you will need to be using jQuery, Twitter Bootstrap, and have a Google Analytics account to use the following snippet.

// ------------------------------
// GOOGLE ANALYTICS CTA TRACKING
// -----------------------------
$('.btn').click(function() {
var text = $(this).text();  // Grab the text from the button
var index = $('.btn').index(this); // Grab the button index (what button it is on the page)
var humanIndex = index + 1; // Button index usually starts at 0, so lets add 1 to make it human readable.
var trackedText = text + ' (' + humanIndex + ')'; // Set the recorded value, for example "Download (3)" for the third download button on the page.
ga('send', 'event', 'Button', 'Click', trackedText);
});

Basically what this code does is upon a button click if grabs the text of the button, the index of the button (what number button it is on the page), and then concatenates the two and records it as an event.

For example, you might have three buttons on a page in the below order

  1. Subscribe
  2. Learn More
  3. Subscribe

In Google analytics they would be recorded as:

  1. Subscribe (1)
  2. Learn More (2)
  3. Subscribe (3)

The “index” is important in discerning which button is being clicked in the case of having multiple buttons with the same text.

At the end of the day you can create a custom report in Google Analytics, like the one below, to drill down events to the page level and see what buttons people are clicking on every page.

Bootstrap button click report in google analytics

Anyways, there are probably a million ways to do this more efficiently, but this is a first crack at it, and it seems to be working so there ya go!


Subscribe for More!


I send out a monthly newsletter on various topics.

Take a moment to enter your details, and you can select the news you would like to have delivered to your inbox!