1

I have created the following tag in GTM (Google Tag Manager):

(function(window) {
    if (typeof(dataLayer[dataLayer.length-1].count) !== "undefined"){
        dataLayer.push({'count':dataLayer[dataLayer.length-1].count+1});
    } else {
        dataLayer.push({'count':1});
    }
})(window);

Initially, when there is no "count" pushed to the dataLayer, the if statement returns false and { "count" : 1} is pushed. After that the value of count should be incremented with each push. My aim is just to count the number of clicks on certain button.

However, it seems "if" statement is never validated, thus every button click results in pushing "0"-s to the dataLayer. I know this is not the best solution, but still I can't find out why this is not working. Btw it's working when I run this code in browser console.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204

1 Answers1

0

I had to use dataLayer.length-2 instead of dataLayer.length-1 to access count. This was caused by the fact that GTM pushes gtm.click to dataLayer after each click event