gnoodle
gnoodle

Reputation: 178

Google Tag Manager: return position in the DOM of the tracked link/element, {{Click Element}} variable

Background description:

I am tracking clicks on links on a web page using Google Tag Manager (GTM) and have set this up successfully, together with python code to extract the data from the API. However, GTM currently doesn't return any indication of the position on the page of the link clicked. I would like to put in the Event Label the position in the DOM of the clicked element.

The purpose of doing this is twofold: Firstly, so I can distinguish identical links (i.e. links which have the same link text and which go to same destination). Secondly, so that I can identify which of the many sections of the page the link is in: is it in the sidebar, on the top bar, in the main content etc.

Problem

I have tried using the {{Click Element}} variable, but this only returns the href of the link, not the position on the DOM.
This is puzzling because when I go into Preview mode in GTM and have a look at the data layer, I see very clearly that there was a push API call to send the DOM location:

dataLayer.push({  
  event: 'gtm.click',  
  gtm.element: 'https://  [rest of URL]   : html.js.yes-js.js_active >   
               [lots more DOM elements separated with >s of which I am only including a few]    
               > div#page-container > div#et-main-area > div#main-content > h3.rpwe-title > a',  
  gtm.elementClasses: '',  
  gtm.elementId: '',  
  gtm.elementTarget: '',  
  gtm.elementUrl: __*~~URL~~*__,  
  gtm.uniqueEventId: 425  
})

And in the "Variables" tab of the GTM preview page, Click Element shows up just as above: it is a Data Layer Variable, it is a string, and its value is given as first the URL, then a colon, followed by the long description of where the link is on the DOM, with all the parents starting from the root of the document, all the way down until the clicked link.

So why, when I add the {{Click Element}} variable to the GTM Event Label, does this only return the href of the link, not the position on the DOM? I submit the changes and publish a new version in GTM, then go to Google Analytics, and only the link href shows there.

What I have tried

Going into the DevTools in chrome (right click, Inspect) and entering the console and typing dataLayer shows that some events, e.g. gtm.elementVisibility, do have a gtm.element object which seems pretty vast. In this gtm.element object, you can click on parentElement which then has its own parentElement and so on until the top level of the DOM. So this data is clearly all there.
To access it I tried a Custom JS variable in GTM which used JSON.stringify to convert Click Element into a string. This didn't work, I suspect because the gtm.element object is too complex, with nested objects and circular references to many locations within the object.
I don't know Javascript, I am groping in the dark with it, I just want to get a nice string through to Google Analytics and from there to my python code where I can manipulate it as necessary.

Possible solution which isn't practical

In GTM I could make multiple triggers for the same event, and specify for each trigger that Click Element matches the CSS Selector for each of the sections of the page. However that would require a separate trigger for each section, which would get messy if I ever need to update the trigger settings. It also wouldn't help me distinguish between identical links.

Question

Why isn't the above working nicely, and how can I accomplish this (preferably with minimal javascript coding...)? Thanks!

Upvotes: 0

Views: 1532

Answers (1)

gnoodle
gnoodle

Reputation: 178

Simo Ahava has a great blog post about exactly this question, at https://www.simoahava.com/analytics/create-css-path-variable-for-click-element/ (no idea why multiple google searches didn't find this...)

As suspected in the question, he explains that Click Element is not actually a string with the location of the link in the DOM, as the GTM Preview mode indicated. It is a complex HTML element.

He goes on to provide javascript code which takes this complex Click Element and extracts the location in the DOM of the link:

function() {
  // copied from https://www.simoahava.com/analytics/create-css-path-variable-for-click-element/
  // Build a CSS path for the clicked element
  var originalEl = {{Click Element}};
  var el = originalEl;
  if (el instanceof Node) {
    // Build the list of elements along the path
    var elList = [];
    do {
      if (el instanceof Element) {
        var classString = el.classList ? [].slice.call(el.classList).join('.') : '';
        var elementName = (el.tagName ? el.tagName.toLowerCase() : '') + 
            (classString ? '.' + classString : '') + 
            (el.id ? '#' + el.id : '');
        if (elementName) elList.unshift(elementName);
      }
      el = el.parentNode
    } while (el != null);
    // Get the stringified element object name
    var objString = originalEl.toString().match(/\[object (\w+)\]/);
    var elementType = objString ? objString[1] : originalEl.toString();
    var cssString = elList.join(' > ');
    // Return the CSS path as a string, prefixed with the element object name
    return cssString ? elementType + ': ' + cssString : elementType;
  }
}

This returns something looking like 'HTMLDivElement: html > body > div#blog > div.hasCoverMetaIn#main' where div is the type of element, element class(es) follows the period (.), and element id follows the hash (#).

So thank you to Simo Ahava, hope it is OK to share his code here. See his article for fuller explanation

Upvotes: 1

Related Questions