Google Tag Manager event tracking using data attribute elements

On the last #tip we talked about how to debug/qa our data attributes , and now we’re going to learn about how to natively track events/social interactions within Google Tag Manager .

We’re going to learn it, basing our tracking on Google Analytics Events and Social Interactions. Of course this can be expanded to any other tool just changing the data attributes, but hey, this is about to learning not about give me a copy and paste solution.

Let’s start saying that data-* attributes it’s and standard HTML5 mark up that we can use to manage our page functionality based on that data instead of relaying on classes or id.
A data attribute is intended to store values that are mean to the page or application and that doesn’t fit in any other appropiate attributes.

In our care the data that we’re storing is the hitype that we’ll be firing. In our example it could an “event” or a “social interaction” . For this we’re setting a data attribute named “wa-hittype“, and this attribut will hold the current hit to be fired, in our case “event” or “social”.

We’ll be using some other data attributes to define our events category, action, label, value and non-interactional switch, please take a look to the following table for more details:

Data Attr Description
data-wa-hittype Type of hit we want to fire on user’s click
data-wa-event-category The Category value for our event
data-wa-event-action The action value for our event
data-wa-event-label *optional. The label for our even
data-wa-event-value *optional. The value for our event if any
data-wa-event-nonint *option. Is the event non interactional?

Let’s check an example:

 data-wa-event-action="Add To Cart" 
>Add To Cart<a/>

So we have a data attribute that will allow us to know when fire a tab based on a CSS selector, and we’ve too all the info needed to populate the information for our event.

Next step is to configure some variables to read these values when the user clicks on the element.

So now when the user clicks on some element, we’ll have all our event needed data on those new variables. Let’s work on the trigger that will make our tag to fire.

We’re using the In-build {{Click Element}} Variable and some magic with a CSS Selector.

There we’re, now we just need to setup our event tag, add our variables to the tag fields, and set the trigger on this new event tag.

Now everytime you need to track a new click on some page element, you’ll just need to ask the developers to add some “standard” data mark-up to the right element.  Even if you do something wrong, the variables will take care of fixing the values were possible (like an event value expecting an integer value instead of a string) or setting a right boolean value for the non-interactional switch for the event.

Any suggestion or improvement to this tracking method is welcome 🙂

P.D. Yeah! I know I talked about tracking Social Interactions too, but I’m pretty sure that you’ll be able to figure it out. Think about like a good moment to learn how to do things instead of just trying to copy and paste and hoping it will work.

#Tip – How to quickly debug/qa data attributes

With the years I learned that using CSS selectors to track user actions is really great but sadly I learned too that it’s really dangerous too.

It’s true that we won’t need to ask the IT team to add some dataLayer or ga pushes into the page, and therefore saving a lot of precious time, but in the other side, any single page update or testing will break our tracking.

Now I try to use data attributes whereas is possible, since those are more likely going to be kept for layout updates.

Checking elements for data attributes can be a tedious task, so I’m going to show you a little piece of code that I hope will make your life easier if you based some of your implementations on data attributes.

On this little snippet is where the magic happens:

(function() {
    var elements = []'*')).filter(function(el) {
        if (typeof (el.dataset) != "undefined")
            return Object.keys(el.dataset).length != 0;
    var data = [];
    var i = elements.length;
    while (i--) {
        var el = JSON.parse(JSON.stringify(elements[i].dataset));
        el["_element_type"] = elements[i].nodeName;


As an example I’m going to show you the output for Google Tag Manager‘s Homepage.

This has been a great time saver for me. Hope you find it useful too 🙂

Keep your dataLayer integrity safe using Custom JavaScripts in Google Tag Manager

In JavaScript when you want to copy an object into another variable is not an easy as doing var myVar = myObjectVar; and you should be really careful when working with your dataLayer info in your customHtml Tags and your Custom Javascript Variables.

Let’s try to explain this is the best way I can. When  you’re doing that you’re not copying the current object data to a new variable but instead you’re pointing your new variable to the object one.

What does this mean?, that if that you change a value into your new variable that change will be reflected in the original one. Let’s see an example:

var OriginalData = {'a': 1, 'b':2};
var CopiedData = OriginalData;

CopiedData.a = "MEC!";

console.log("Old 'a' Value: ", OriginalData.a);

Before trying it in your browser console, could you please think what will be “mydata.a” value printed into the console?. If you’re thinking on a “1” value I’m sorry to say that you’re wrong:


You may be thinking, why “OriginalData.a” has changed if we only modified the value for our “CopiedData” object.

In programming you we can pass the data in 2 ways:

Call-by-value: This means that the data from the original variable will be copied/cloned into the new variable. 

Call-by-reference or Pass-by-reference: This means that the data on the new variable will be a pointer/reference to the original varialbe one. So if we want to print CopiedData.a , instead of returning a value, it will go to get the value to OriginalData.a (where CopiedData.a POINTS TO) .

How the data is passed in the different programming language is specific to each language, but let’s take a look on how JavaScript does it. Basically any variable type but the object will be called by value. If we do the same example as above, but instead of using an object we use a integer, we’ll be getting a different behaviour.

var OriginalData = 1
var CopiedData = OriginalData;

CopiedData = "MEC!";

console.log("Original Object 'a' Value: ", OriginalData);
console.log("Copied Object 'a' Value: ", CopiedData);


As you can see if the variable to be “cloned” is not an object, it will be “passed by value“.

So we need to take in mind that we may be overwriting the original object values. When working with GTM variables, this may equal with updating the original dataLayer values.

There’s not any in-built way to do a deep copy of an object in JavaScript. As we’re mostly refering to data, we could just stringify our object and then parse it again ( never use eval() for converting ).

So when trying to make a copy of some object from the dataLayer (for example when working on a Enhanced Ecommerce implementation and using variables to feed our hits). I would recomend doing it this way:

var ecommerce = JSON.parse(JSON.stringify({{ecommerce}}));

This will only work for objects not including functions/date values/etc. Just plain data. But for now it will keep our dataLayer integrity safe.

Just googleing a bit, you’ll find some functions around to make a full deep copy of an object, but we’re just working with data, so we’re not going to cover that at the moment.

Tips for working with Custom HTML & Custom JavaScript tags in Google Tag Manager

This time I’m writting down some tips for when you guys are playing around with the custom HTML tags or custom JavaScript variables not only for Google Tag Manager, but for any other TMS or website.

Most times due the projects deadlines or maybe just lazyness, the code we use (I include myself here), is not fail proof, and we need to think that we may broke some page functionality or even some page load. So using customHTML/custom JavaScript is a serious thing. Even a lot of companies are forbidden to use them in Google Tag Manager.

  1. Don’t use lazy/generic variable names

    As you all know (right) all the scripts share the same window object. So if you declare a variable

    myVariable = "myValue";

    you will then be able to get that variable value from the main window object


    and this means that if we using some variable like “counter”, and another script uses it, it’s going to be overrided. D’oh, our loop just became a neverending loop (indeed, that’s not good).

  2. Always use “var” for declaring your variables if you are not planning to use them as a global data

    Usually you may think that declaring a variable inside a function will make it just available inside that function, but that’s not right, if you declare a variable without using “var”, it’s gonna became a global variable, if you want to try it, create a new tag an put this code on it:

           myVariable = "myValuetest";

    Now if you go to your console you will notice that windows.myVariable is there. Even if it was inside anonymous function, it became a global variable.

    This is the right way to do it:

           var myVariable = "myValuetest";
  3. Always check for the variable value before doing something with it

    Usually being a lazy programmer will lead to problems, I know that it takes a lot of time to get everything checked as it should, and our code may be working for us in our tests, but we need to think that there will be thousands of users, with different browsers, browser versions, internet connections (some things may load slow, or not even load) , pluggins installed, and that’s why we need to perform the checks in the right way, we’re interacting with a client-side tracking, so we just CAN’T cover all the possible situations.

    Take this simple screenshot as an example:

    Let’s see how should we had code the previous snippet:

    Instead of printing an error, we could have send an error event, in order to track on which pages that errors is happening, for which browsers, or at which time 🙂

  4. Be careful with the loops, always set a break in the case the condition is never met

    We may need to loop around some array, for example, we want to grab all the product SKU for our transactions to pass that data into a marketing pixel. For that we’ll need to loop thru all the ecommerce.purchase.products . but we need to be sure that our loop will end at some point. For the previous example it’s easy, as we’ll easily know when it needs to end (when there’re no mor products in the array).
    But let’s think on another example. We want to wait for some object to be available to fire something, and for that we use a setInterval to check for the variable availability each 100 milliseconds.

    Let’s see some code for this:

    var checkExist = setInterval(function() {
      if(typeof(window.myObject)!="undefined") {
      }, 100);

    Hey, it works, it sets an interval each 100 milliseconds and get our object is already available it clears the interval. We tested it, and it works, we’re so proud of ourselves. But this time we didn’t consider what will happen IF that object NEVER gets available… yep, you’re right that code will be running forever, and depending on the code that it’s ran inside it, it may kill the user’s browser.

    If using loops in Variable you may need to take in mind that variables are being ran several times (not just once), so the problem is going to be even bigger.

    In this case we could have an incremental counter, so we could exit the interval execution, after 20 tries (20×100 = 2seconds).

      var counter = 0;
      var checkExist = setInterval(function() {
            if(counter > 20)
      if(typeof(window.myObject)!="undefined") {
        }, 100);

    So always think on a way for our loops to end in the case the condition is never met.

Getting super clean content reports in Google Analytics using GTM

In Google Analytics the urls are case sensitive, therefore in our content reports /index.html will be different to /Index.html, and querystring values will make Google Analytics to think that even if it’s the same page it will recorded as a new one, /index.html?cache=off and /index.html?cache=on will be recorded as 2 different pageviews for example.

The first problem its easily fixable with a lowercase filter within the views, but the querystring parameters it’s going to be a problem … I bet you’re saying that you can just add them to the Exclude URL Query Parameters list within your view configuration page and Yes! that’s right, but I’m pretty sure that you’re likely going to end having some marketing campaigns adding new parameters, or IT adding some parameters to get some funcionality switched on (like enabling some caching feature or whatever).

So today, we’ll be using Google Tag Manager to solve this problem of having all our content reports fragmented due the unexpected querystring parameters in our pages. So let’s think about it, wouldnt be easier to identify the real parameters and getting ride of the rest that are not expected for the page functionality?, If you think about it, it’s likely a better way to do it, we can know which parameters will be used in our site, but we cannot think on unexpected ones.

To achive this, we’re going to make use of just one single variable in Google Tag Manager, yeah that’s it, just one single Custom Javascript variable.

We’ll just need to configure the paramList array on the code top, and add there all the querystring parameters that we want to keep. Any other parameter that is not listed in our array will be removed from the querystring value that is going to be recorded by Google Analytics

        // We'll need to defined the QS values we want to keep in our reports         
        var paramsList = ["two","one","three"];

        // CrossBrowser inArray polyfill 
        if (!Array.prototype.indexOf) {  
            Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {  
                "use strict";  
                if (this == null) {  
                    throw new TypeError();  
                var t = Object(this);  
                var len = t.length >>> 0;  
                if (len === 0) {  
                    return -1;  
                var n = 0;  
                if (arguments.length > 0) {  
                    n = Number(arguments[1]);  
                    if (n != n) { // shortcut for verifying if it's NaN  
                        n = 0;  
                    } else if (n != 0 && n != Infinity && n != -Infinity) {  
                        n = (n > 0 || -1) * Math.floor(Math.abs(n));  
                if (n >= len) {  
                    return -1;  
                var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);  
                for (; k < len; k++) {  
                    if (k in t && t[k] === searchElement) {  
                        return k;  
                return -1;  
        var qsParamsSanitizer= function(qs,permitted_parameters){
        var pairs = qs.slice(1).split('&');
        var result = {};
        pairs.forEach(function(pair) {
            pair = pair.split('=');
            result[pair[0]] = decodeURIComponent(pair[1] || '');

        var qsParamsObject = JSON.parse(JSON.stringify(result));
        for (var p in qsParamsObject){
                delete qsParamsObject[p];
        var rw_qs = '?' + 
                Object.keys(qsParamsObject).map(function(key) {
                    return encodeURIComponent(key) + '=' +
        if(rw_qs=="?") rw_qs="";
        return rw_qs;
     return qsParamsSanitizer(,paramsList);
       // let's let GA to use the current location.href if
       // for some reason our code fails.
       return undefined;

Now, we only need to set our pageview tag “page” parameter so Google Analytics uses the new sanitized array instead of the one that it’s on the url.

We’re done!. Let’s see how it works with a screenshot

Now you just need to sit down, and wait some hours to start seeing your reports in a clean way and with no fragmentation. Happy analyzing!



Tricks to deal with customized Google Analytics and Google Tag Manager integrations

In the past years, I worked on implementing Google Analytlics and Google Tag Manager in a lot of differences scenearios and almost any kind of integrations. So I’m gonna show you some code snippets that may help you integrating Google Tag Manager and Google Analytics into your libraries in the best way possible.

Checking is Universal Analytics is available

Most integrations I’ve seen does check for the ga object within the DOM before trying to push something to it. This is really nice, and a check that should be done ALWAYS, but Universal Analytics allows you to change the default name for the “ga” object, so under those situations our code may not work as we’re expecting.

Luckly for us, Universal Analytics creates another variable, named window.GoogleAnalyticsObject, that will allow us to grab the current object name being used by Universal Analytics.

So using the following code will allow us to check is Google Analytics is really available even if the current name has been changed:

if(window.GoogleAnalyticsObject && typeof(window[GoogleAnalyticsObject])=="function"){ 
   // Code Here

Checking for current dataLayer object name for Google Tag Manager

Google Tag Manager users the “dataLayer” name by default, but it may changed to use any other name.

This piece of code will allow us to find the right dataLayer name dinamically:

var gtm_datalayer_names=[];
    for(i in google_tag_manager){

The we could do something like:


We’ll even be able to send pushes to all the different dataLayer available on the current page:

        var i = window.gtm_datalayer_names.length;
           var dlName = gtm_datalayer_names[i];
           window[gtm_datalayer_names] = window[gtm_datalayer_names] || [];                 
              'event': 'my-event-name',
              'dataLayerName': gtm_datalayer_names[i]

Debugging and monitoring GTM Variables for errors

Google Tag Manager does not throw any error when the code in a variable fails. This is not bad per se as it would save us from having our sites failing if something is not coded as it should, but it will blind us agains some minor errors that may not be noticiables, for example if our Enhanced Ecommerce is failing for a certain product, or from some specific browser.

Thanksfully we can use try{}catch(e){}Lee el resto de la entrada


Enabling Optimizely native Google Analytics Integration within Google Tag Manager

As you may already know, Optimizely has an in-built Google Analytics integration, which will allow us to track the experiments and variations being showed to a client using custom dimensions.

For enabling them, you’ll need to put the following lines after the create command and the pageview one:

window.optimizely = window.optimizely || [];

This is a bit tricky when using Google Tag Manager native tags, since it doesn’t allow you to execute anything after … Lee el resto de la entrada


Finding pages missing Google Tag Manager snippet within Google Tag Manager

This time, we’ll be using Google Tag Manager itself, to find pages in our site that may be missing Google Tag Manager. Ok, it may sound strange, but was not able to find any other way to say it .

Basically we’re going to use a custom html tag, to detect is the previous page had loaded Google Tag Manager code.

To achive this we’ll be using a single Custom HTML tag ,a cookie and … Lee el resto de la entrada


Tracking the Hover Intent with Google Tag Manager

At the moment, Google Tag Manager listeners are limited to Form Submits, Link Clicks and Clicks (for any DOM element). We are going to write a custom listener for hover intents by users. This means that we’re not only to do something when the user pass the mouse pointer over an element, but instead we’re waiting a certain time with the mouse over the element before submitting the action to GTM.

For this we’re … Lee el resto de la entrada