Add a Click Heat Map to your Website using Google Analytics and Google Data Studio

Here we provide a streamlined version of the post by CompassRed Data Labs posted in medium.com.

Taking advantage of the free version of Google Analytics, this tutorial will give you the steps to follow to create a click heatmap for your website. In this case we monitor all the clicks done on your website, but you have the option to register clicks done to links only.

What should you use a click heat map for?

This helps you get data to see what users interact with in your website. Maybe you had doubts about a section you recently added to the page and you want to see if it really gets the attention you wanted from your visitors. That way you can have some insights for future design decisions about how to acommodate your page to make it more attractive.

1. Google Tag Manager account

These are the steps you should follow:

  1. Go to https://tagmanager.google.com
  2. Click create account
  3. Fill the form, in this case we chose Website.

Once you created it, you will be redirected to the workspace for your Google Tag Manager account. A window will pop up and tell you to paste this code blocks in your index.html file for all the sites you want to monitor.

You need to paste this code as high in the <head> tag of the page as possible:

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-YOUR_ID');</script>
<!-- End Google Tag Manager -->

And this other code block immediately after opening the <body> tag:

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-YOUR_ID"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

Notice the YOUR_ID part of each code block, you will need to replace it according to the one generated for your Google Tag Manager account.

2. Create user defined variables

From the left panel, go to variables and first of all, in the Built-in variables click the Configure button and enable Click Text.

And from the User-Defined variables panel, you have to add the variables below, select Custom JavaScript from the the Page Variables section and paste the JavaScript code provided for each variable, then click Save and repeat the proccess for each one of them. The suggested name for the variables is in bold characters.

JS - Click Text Clean. Provides a clean version of the text the user clicked on. The code checks if Click Text (which we enabled before) is defined, if it's not, the text will be labeled as undefined. The result text is also truncated to 100 characters if the text is longer than this and everything is converted to lowercase.

function() {
    var output;
    var input = {{Click Text}};
 
    if (input == null || input == '') {
        output = 'undefined';
    } else if (input.length > 100) {
        output = input.substring(0,100).toLowerCase() + '...';
    } else {
        output = input.toLowerCase();
    }
    
    return output;
}

JS - Click X Coordinate. Measured in pixels, this variable provides the mouse position in the x-axis where the used clicks.

function() {
    var coordinateX;

    if (event == null) {
        coordinateX = 0;
    } else {
        coordinateX = event.pageX;
    }

    return coordinateX;
}

JS - Click Y Coordinate. This variable does the same as the previous one, but this time for the y-axis.

function() {
    var coordinateY;

    if (event == null) {
        coordinateY = 0;
    } else {
        coordinateY = event.pageY;
    }

    return coordinateY;
}

JS - Screen X Coordinate. Provides the total width of the user's viewport.

function () {
    var body = document.body;
    var html = document.documentElement;
    var width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth);
 
    return width;
}

JS - Screen Y Coordinate. Provides the total height of the user's viewport.

function () {
    var body = document.body;
    var html = document.documentElement;
    var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
    
    return height;
}

JS - Relative X Coordinate. Taking the Click X Coordinate and dividing it bythe Screen X Coordinate we are able to create an index. This should adjust for the variability of different screen sizes.

function() {
    var clickCoordinateX = {{JS - Click X Coordinate}};
    var screenCoordinateX = {{JS - Screen X Coordinate}};
    var relativeX;
    relativeX = (clickCoordinateX / screenCoordinateX).toFixed(2);

    return relativeX;
}

JS - Relative Y Coordinate. Does the same as the variable above, but this time for the Y Coordinate.

function() {
    var clickCoordinateY = {{JS - Click Y Coordinate}};
    var screenCoordinateY = {{JS - Screen Y Coordinate}};
    var relativeY;
    relativeX = (clickCoordinateY / screenCoordinateY).toFixed(2);

    return relativeY;
}

Also, we neet to create a Google Analytics Settings variable, which you can do as follows:

From the main dashboard in your GA Account, click Admin in the bottom left corner.

And from the center column, click Tracking info and then Tracking Code.

Copy the Tracking ID, since you will need it in the next variable, which we name GA Settings.

Click the New button and scroll down to the Utilities section to choose Google Analytics Settings, then paste the value you copied in the Tracking ID:

3. Create your trigger

From the left panel, choose Triggers and click the New button. For this example, we picked the All Elements option from the Click section, and firing the trigger on all clicks as the image below shows.

This is the simplest version, you can let your creativity run free and opt to choose a trigger to fire only on link clicks and/or only in certain pages.

4. Create your tag

From the left panel, choose Tags and click the New button. Fill the form as shown in the image, the value to set in the Event Label field is this:
pu:{{Page URL}}|ct:{{JS - Click Text Clean}}|rx:{{JS - Relative X Coordinate}}|ry:{{JS - Relative Y Coordinate}}.
This string lets us collect a range of data which we later use in Data Studio. You may notice that everything is split by the delimiter | (pipe character). We used key-value pairs to make it easy to remember what each delimited space of the colected data represents.

You need to select the trigger we created previously too, so the final result for the tag should look like this:

Once this is done, you need to publish your tag with the Submit button on the top right corner. Add the version name and description you want and then click Publish.

5. (Optional) Check your results in Google Analytics

Go to the Google Analytics main dashboard and you can check the current activity on your website by clicking Realtime and then Events.

6. Build a report in Google Data Studio

You can use any tool that can work with data generated from Google Analytics, for this example we use Google Data Studio because it is free and simple to set up.

Create a new report and connect to your GA account

Go to datastudio.google.com and click the big + to create an empty report. You will need to connect to a Data Source. Click Create New Data Source and choose Google Analytics, then find Account > Property > View where your generated data exists.

Create custom fields

Now it is time to use that long Event Label created in GTM. We need to break it apart into individual pieces with some regular expressions added below. You should not have any errors if you followed the naming conventions for the variables created before.

Open de Data Source Editor by going to the menu Resource>Manage added data sources and then click Edit on the corresponding data source. If you are adding the data source for the first time, you would be able to skip these steps.

We will need to add some custom fields, so for each one you have to click on the Add a Field button, set a name for the custom field, paste the provided code and click Save.

Event Label - Page URL. Extracts the Page URL from your Event Label.
REGEXP_EXTRACT(Event Label,'pu:(.*?)(\\||$)')

Event Label - Click Text. Extracts the Click Text from your Event Label.
REGEXP_EXTRACT(Event Label,'ct:(.*?)(\\||$)')

Event Label - Relative X. Extracts the Relative X Coordinate from your Event Label.
REGEXP_EXTRACT(Event Label,'rx:(.*?)(\\||$)')

Event Label - Relative Y. Extracts the Relative Y Coordinate from your Event Label.
REGEXP_EXTRACT(Event Label,'ry:(.*?)(\\||$)')

The last thing you need to do is duplicate the Event Label - Relative X and Event Label - Relative Y fields. That way you can store one version as Text and the other as Number, be sure to change the data type to Number and for convenience reasons, change the name of the field to give a distinction. Once that is done, your custom fields should look like this:

Create the heatmap visualization

As recommended by CompassRed, we used Fireshot Chrome Extension to take a screenshot of the whole website and save it as an image.

Once you have your screenshot, insert it as an image on your dashboard and size it appropiately.

Next, you need to create a scatter plot visual and add the following fields to your visual. Select the fields according to the image below:

7. Results

Styling is up to you, the only thing you need to do is to reverse the Y-axis so the clicks (circles) are located where the user actually clicked on your page.