Learn business growth with Google Analytics 4 Forums Google Analytics 4 Implementing HTML Custom Attributes with Google Tag Manager for Tracking Button Clicks Reply To: Implementing HTML Custom Attributes with Google Tag Manager for Tracking Button Clicks

  • Jacob

    Member
    21 April 2023 at 7:35 am

    Alright, let’s break this down into three steps:

    1. Start by creating a ‘Custom JavaScript Variable’
    Here’s a screenshot of how to do it
    enter image description here
    Then, use this code:

    `
    function(){
    // Getting the clicked element
    var clickElement = {{Click Element}};

    // Making sure we have the parent element we want. If not, we return ‘false’
    if(!clickElement.closest(“div.stepped-selection__list-item”))
    return false;

    // Checking if the parent dom has the attribute we want.
    // Returns the attribute value if it’s there, ‘false’ if it’s not.
    var modelListDom = clickElement.closest(“div.stepped-selection__list-item”);
    if(modelListDom.hasAttribute(“data-trackervalue”)){
    return modelListDom.getAttribute(“data-trackervalue”);
    }
    return false;
    }
    `

    2. Now, let’s create the trigger
    Here’s another screenshot for you:
    enter image description here
    Start with the ‘click element’ > ‘match css selector’ to nab all the elements inside the selector. You can tweak this a bit to suit your case. Then, use the ‘Variable’ we created in step1. If this gives back ‘false’, we don’t want to trigger the tag.

    3. Next up, Create the Tag
    Doing the ‘Tag’ config is the easy bit. Just take the ‘Trigger’ from step2, name the event and event parameter to your liking. Finally, set the event parameter value as the ‘Variable’ from Step1.