Petroc3lli
Petroc3lli

Reputation: 23

How to capture the text near a button click for the event label

I'm tracking some asset downloads using Tag Manager. There are multiple downloadable assets on the page, each with a 'Download asset' button.

I want to create a single tag in tag manager to cover all of these downloads, using the event label to specify the type of asset: eg 'full-bleed image', 'facebook ad image' etc.

Ordinarily, I'd use the 'click text' or 'click URL' variables for this but I can't on this occasion. All of the download buttons have the same text (apparently, this can't be changed) and the URL just includes a CMS-generated asset number as opposed to a descriptive URL.

However, above each button there is a h4 that includes the name of the asset:

Is there any way to create a variable in tag manager that will scrape the content of the h4 just above the button when it's clicked?

I created a variable for the h4 but it just captures the content of the first h4 on the page (and not the one nearest to the button click).

<div class="content">
     <h4>Full Bleed</h4>
     <div class="copy">
          <p>Perfect for social media.</p>
     </div>
     <div class="btn-container">
          <a href="URL?assetNo=17232568" class="btn" >Download assets 
          </a>
     </div>
</div>

Upvotes: 2

Views: 1052

Answers (1)

Matus
Matus

Reputation: 1418

Yes there is a way to do it. It requires some scraping.

You can create a new custom JavaScript variable and use built-in variable {{Click Element}} - then get it's parent node, e.g.:

{{Click Element}}.parentNode

This should return whole <div class="content"> element. Then simply search inside that element for <h4> like so:

{{Click Element}}.parentNode.getElementsByTagName("h4")[0]

  • this is your "Full Bleed" element. Remember that this returns an array, thus [0].

One thing to note is that when you click on your element:

<div class="btn-container">
      <a href="URL?assetNo=17232568" class="btn" >Download assets 
      </a>
</div>

depending on where exactly you click the {{Click Element}} will sometimes be <div> element and sometimes <a> inside of it. This would break ".parentNode" functionality sometimes so you will need some checks. Below I write some pseudo code (not tested and messy):

Custom JavaScript variable:

function(){
  var parent = {{Click Element}}.parentNode;
  var value = "";
  if(parent.className === "content"){
    value = parent.getElementsByTagName("h4")[0]
  }else{
    value = parent.parentNode.getElementsByTagName("h4")[0]; // you need to go one level above
  }
  
  return value.innerText;
}

Upvotes: 1

Related Questions