简体   繁体   中英

Click Element with CSS selector is not working in Google Tag Manager

How do I detect a click on the following element using "Click Element" variable in Google Tag manager:

<a href="https://amazon.in/product-id" target="_blank" class="amazon-btn">
    <div>
        <span>BUY NOW AT</span>
        <div class="amz-logo"></div>
    </div>
</a>

I have created the following trigger:

Click - All Elements -> Some Clicks -> Click Element -> matches CSS selector -> *.amazon-btn*

在此处输入图像描述

This doesn't trigger on clicking the element.

The following is the click element in the debug window:

'HTMLDivElement: html > body > section.content.looking-sec > div.container > div.row > div.col-md-6.looking-cont > div.btn.btn-custom.btn-top.hide-small > a.amazon-btn > div'

在此处输入图像描述

I even tried, Click Element -> contains -> amazon-btn . That doesn't work either.

Try the click on anchor element instead

Don't use "Click > All Elements"

Use "Click > Just Links"

And then apply your CSS selector

Here's the issue, Click - All Elements trigger returns the actual element that was clicked (obviously) but then that could be just an icon in a bigger button. Whereas we want to capture the click anywhere on the button or the target element. More about this at this link

This is what I ended up using. I created a custom javascript variable Get All Classes :

function() {
  var el = {{Click Element}};
  var ad = el.nodeName.toLowerCase();
  if(!el.className==''){
    ad = ad+'.'+el.className.replace(/\s/g,'.');
  }
  var i = 0
  while(el.parentElement.nodeName.toLowerCase() != 'body' && i < 50){
    el = el.parentElement;
    var st = el.nodeName.toLowerCase();
    if(!el.className==''){
      st = st+'.'+el.className.replace(/\s/g,'.');
    }
    ad = st+'>'+ad;
    i++;
  }
  return ad;
}

This returns a string with all the node names and their classes starting from the clicked element to all the way till the <body> element. Like this: body>div.main-container.content>p.first-section>a.amazon-link And then I am using this variable in the trigger to check if it contains a particular class. 在此处输入图像描述

Is there an easier and better way to get the value of {{Click Element}} GTM variable in the form of string as highlighted below? If so, please add it as an answer and I'll accept that as a correct answer. 在此处输入图像描述

In the Trigger Configuration, try adding this condition:

Click Element matches CSS selector .amazon-btn, .amazon-btn *

I haven't tested this, but it should work when the element with the amazon-btn class is the click target, or any child inside of that element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM