简体   繁体   中英

How can i use Custom attributes of html in Google tag manager to track clicks on lots of buttons

I have some long lists of buttons. For example, i have one single list of car models that all have the same custom data attribute of "modellist", while they have also another data attribute which is the name of that car model (Note that these buttons are NOT links). the attached image Now, without the need of creating a single tag for each and every one of these buttons, i need to find a faster way for this case using the google tag manager and GA4 (google analytics 4), so that i would be able to track clicks on these buttons. Does anyone know how can i do this? I very highly appreciate your help & support here.

Here are the steps and how to do it.

1. Create a Custom JavaScript Variable ;

Here is the Screenshot在此处输入图像描述

The code is:

function(){
  // Get the click element;
  var clickElement = {{Click Element}};

  // Check there is a closet parent element you want. If it doesn't then return false;
  if(!clickElement.closest("div.stepped-selection__list-item"))
    return false;
  
  // Check the parent dom has the attribute you want. 
  // If it does, return the attribute value. Otherwise, return false;
  var modelListDom = clickElement.closest("div.stepped-selection__list-item");
  if(modelListDom.hasAttribute("data-trackervalue")){
    return modelListDom.getAttribute("data-trackervalue");
  }
  return false;
}

2. Create the trigger

Here is the screenshot:

在此处输入图像描述

First, using the click element > match css selector > To catch all the element inside the selector. You can modify it a bit to make it more suitable in your real case.

Second, the Variable we create in step1. It will return false if something not we expected. So we don't want to trigger the tag if the Variable is return false.


3. Create the Tag.

The Tag config is the easiest one.

Just use the Trigger in step2.

And give the event name and event parameter you would like.

Give the event parameter value as the Variable in Step1.

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