Get text of clicked button in Google Analytics - google-analytics

I want to be able to know exactly which element from a class has been clicked. I enabled the text option in Tag Manager:
But it's still not visible in the click object. But it wouldn't pick it up, since the tag containing the text is nested in the clickable element. Can I add a custom HTML attribute to be able to identify which element has been clicked?
<div class="card-content"> //<---- clickable element
<i aria-hidden="true" class="card-icon material-icons">business</i>
<h3 class="card-title">Company details</h3> //<--- clicked text
</div>

The best way to figure it out is to use the "Preview & Debug":
Activate it
Go to the page where you want to test (you should see now a new box at the bottom)
Click on the element
Check the variables in the debug box. Especially check the click.element data.
My guess is that since there is no "real" text in the div box, just children tags, no text can be discovered.
There are different options to solve it:
add the text as data-attribute to the div and use the click.element data
use a data-layer push event
if you know JS you can use the click.element data in a JS variable and traverse down to the h3

If you are going to keep your code as it is, you could create a custom variable, using Custom JavaScript.
In order to do so you need to first create the custom variable, choosing the Custom JavaScript type:
This code should do the job (I tested id)
function() {
return {{Click Element}}.closest('.card-content').getElementsByClassName('card-title')[0].innerText;
}
The custom variable will return the text inside .card-title.
To test the custom variable, you may create a dumb HTML tag with a console.log script, replacing Inside TXT with the name you gave to your custom variable:
<script>console.log( {{Inside TXT}} )</script>
The trigger should be a Click All Elements.
When previewing this tag, the captured text should appear in your console, as well as in the debugger panel.
Reading again your question, I wonder if you are going to have several .card-title items inside the .card-content. In that case, this custom variable will not work. Let me know what is the case.
Also, the code could be simpler, but I am not really sure on how is it really going to work in your site, so this one seems more reliable, since it works clicking anywhere in the element.
EDIT:
In order to test it, after you click an element, a new "Click" will appear in the left pane (Summary). There, in the Variables tab, you will see the variables captured by the click. The data will be stored under the variable name you gave to the variable.

Related

GTM - CSS Element

I'm wanting to create a variable to grab the username from a landing page (assuming it's possible). In my attached examples, I'd like to grab the text "Landing_page_test".
I'm just learning CSS so I'm not able to single out just that text.
Any thoughts/suggestions would be much appreciated! enter image description here
Console
Elements Pane of Landing Page
document.querySelector returns an element, not the text. Add .innerText
Try it out on this page: document.querySelector("a.question-hyperlink").innerText to get the name of the question.
But you probably don't want to do it as custom html tag. You probably want to do it on click. in that case, you have {{Clicked Element}} variable in GTM, of which you can also get .innerText, or get its .parentElement and further navigate DOM from the clicked element as you wish and get whatever you need.
Here's the html of the Location & Date/Time text blocks
Text Block

Google Tag Manager not tracking links clicks on images and icons

In Google Tag Manager, I set it up to track some data from clicks on elements that contain a certain class and record an event in Google Analytics. It seems to work just fine for text links, but I run into problems if there is another tag inside the link for an image, icon, etc. For example, the following would work fine:
Click here
But this won't work:
<a href="link.html" class="track_this" data-tracking-info="my info">
<span class="icon click-here"></span>
</a>
And something like this will work if you click on the text, but not if you click on the icon:
<a href="link.html" class="track_this" data-tracking-info="my info">
<span class="icon click-here"></span> Click Here
</a>
I know that I could add the "track_this" class into the span for the icon, but it gets REALLY messy in more complicated scenarios. Like imagine having a thumbnail image with an icon and some text below it all wrapped into one a tag. I'd have to put that class and the tracking info on the image tag, the span for the icon, the div for the text, etc.
Is there a better way to do this? Thanks!
I could speak more definitively on this if I could see how your GTM was setup, but my guess is that you are using an "All Elements" trigger to capture these link clicks, and filtering on "Click Classes" or "Click Element". The issue with this is that, when the link tag (<a></a>) contains another element, such as a <span>, even though that triggers your link to open, the element that GTM records as receiving the click is the span, not the link.
If you want to fix this, there are two options, either of which should work.
The first is to switch to using a "Click - Just Links" trigger type, and filter on the class "track_this". For this trigger, GTM lets click events "bubble" up until they hit a link element, and then it tests your trigger against that link, instead of the element that was clicked on. Simply using this trigger type should work for all three of your samples.
The other option is to use a more advanced filter with the "Click - All Elements" trigger. If you modify the trigger so it fires on "Some Clicks", and then make the condition that "Click Element matches CSS selector:"
.track_this, .track_this *
then it will register a click on any element that has the track_this class, as well as a click on any element inside those elements.
This problem can also be solved using a little bit of javascript and a 'User-Defined Variable' in Tag Manger. This solution is for handling more complex UI components.
Explanation
Google Analytics + Tag Manger record the very specific Element or Node that is clicked by the user. That element is stored in GA as a "Click Element" variable. So in more complex UI situations it is possible the user could click on multiple elements for a single action to occur. For example. Here is a button with an icon and text.
<div
class="button"
id="PARENT_ID"
onClick = () => ...
>
<span id="CHILD_ONE">
icon
</span>
<span id="CHILD_TWO">
text
</span>
</div>
In this scenario it is possible for the user to click on any of the three id's above. All three will activate the onClick action. However, Google Analytics doesn't care about the onClick. It only cares about what specific element was clicked. IE: PARENT_ID, CHILD_ONE or CHILD_TWO.
The "User-Defined Variable" Solution.
In Tag Manager go to the 'Variables'. (Left column menu.)
Add a new 'User-Defined Variable'.
Select the variable type as 'Custom JavaScript'.
Add:
function() {
if ({{Click Element}}.id != "") {
return {{Click Element}}.id;
}
if ({{Click Element}}.parentNode.id != "") {
return {{Click Element}}.parentNode.id;
}
if ({{Click Element}}.parentNode.parentNode.id != "") {
return {{Click Element}}.parentNode.parentNode.id;
}
return {{Click Element}}.parentNode.parentNode.parentNode.id;
}
This script will search the DOM up three levels up from any child Element (Node) and look for a matching Tag id.
NOTE: Click Element is the variable name used by Google Analytics. It's the gtm.element the user clicked.
Setup Tag Manager Configuration to use your new 'Custom Variable'.
Now use the parent id for setting up your Triggers. In my example PARENT_ID will be the returned id even if a user clicks on CHILD_ONE or CHILD_TWO. So select 'contains' PARENT_ID.
------ Further Considerations -----
This solution only works within three parent levels. Also while unlikely it is possible to capture an element out of scope of what is intended.
In more complex UI components it might be preferable to add the Tag id's to every Element. If you are using a front end framework like React I would suggest making the Tag Id a dynamic prop and add it to all child components.
NOTE: Google Analytics changes often. This is a GA4 + Tag Manager solution.
style use pointer-events:none can't tracking by inside.
<a>
<svg id="gtm-track">
<rect style="pointer-events:none"> .... <rect/>
<path style="pointer-events:none"> .... <path/>
<svg/>
<a/>

Using Data Layer to track event based rule

This is kind of confusing. suppose i have implemented a data layer with page details. The page has 2 articles, both gets redirected whenever clicked. Now suppose the tracking goes like this, Once the User clicks on the card, the name of card (h1) name will be reported in the tool. I have implemented this scenario without using data layer. (Looking for custom script in Adobe DTM data element?).
The code is mentioned below where i have defined the data layer. In DTM console I have created data elements, and mapped with the datalayer object. for Card name - DDO.pageData.cardname. Also created an event based rule and mapped with this data element. Problem here is, whenever i am clicking one article, it is taking h1 of both the article in a single evar. Ideally it should take the value of ONLY the article which is being clicked. Please suggest.
<article class="mu-item">
<a href="www.google.com" data-tags="test" target="_blank">
<div>
<h1>This is a test text for tracking</h1>
<p>This was the day when the South Stand at Old Trafford, the stadium where he played around half of his 758 matches for United, was officially renamed in his honour before his beloved Reds took on Everton in the Barclays Premier League.<br><br>
</p>
</div>
</a>
</article>
<article class="mu-item">
<a href="www.facebook.com" data-tags="{{displaytag_2}}" target="_blank">
<div>
<h1>This is new card</h1>
<p>This was the day when the South Stand at Old Trafford.<br><br>
</p>
</div>
</a>
</article>
<span>some text</span>
<script type="text/javascript">
DDO = {} // Data Layer Object Created
var pageObj = {};
var pageDOM = $('.mu-item');
pageObj.DestinationURL = $(pageDOM).find('a').attr('href');
pageObj.cardName = $(pageDOM).find('h1').text();
DDO.pageData = {
"pageName": document.title,
"DestinationURL":pageObj.DestinationURL,
"cardname":pageObj.cardName
}
</script>
<script type="text/javascript">_satellite.pageBottom();</script>
As others have mentioned, the only way to know which h1 value is relevant is to capture it during the click event.
As I mentioned in the comments of your other question
[..] DTM does not currently pass a reference to this to data elements created in the config area
There is no way around this. You must capture it during the click event as I showed you on your other question (custom script within a rule condition). As others have mentioned, making it pass through your data layer is technically an unnecessary step. There are pros and cons to actually doing it, but that's a different discussion.
Assuming you are determined to do it...
Go to Rules > Data Elements, and click Create New Data Element.
Name your data element according to whatever convention you use. For data layers, I personally like to name it the full data layer path, e.g. "DDO.pageData.cardName".
For Type, select "JS Object".
For Path, put the full path DDO.pageData.cardName
Click Save Data Element to save the data element.
Next, go to your Event Based Rule. It should still have your same Event Type (click), and Element Tag or Selector (article.mu-item).
In your Rule Conditions, select "Data > Custom" to add a custom js code box.
In here, you will still need to grab the information based on this. But instead of using _satellite.setVar() to create an on-the-fly data element, you will instead push the value to your data layer.
Example:
var articleTitle = $(this).find('h1').text()||'';
window.DDO
&&
window.DDO.pageData
&&
(window.DDO.pageData.cardName=articleTitle);
return true;
Note: I'm using jQuery syntax to get the h1 text. Based on your previous question you were having trouble with that at the time, so I showed you the vanilla js version. Not sure if you sorted that out or not, but you get the principle.
Now you can use your data layer referenced data element within the rest of your rule's fields %DDO.pageData.cardName%
Your problem is that you have multiple menu items and headlines. You would either have to create an array with all headlines (which would it make hard to get the correct entry for a click) or populate the datalayer only after a click on the element, so it always contains the data for the selected element.
However as I pointed out there is a good chance you do not need this. If you do an event based click rule with an css selector you have available a data element that DTM automatically creates - it's called %this% and contains the clicked DOM node. You should be able to get the text inside the headline with %this.textContent% (you have a nested paragraph in your headline, which I'm not sure is valid HTML, so you must allow event to bubble up in the event rule configuration).

Getting the text value of link when clicked a particular link in a page in adobe dtm rules

Using the source code below, I need to track text values of clicked links.
How can I track this and whether page load rule or event based rule is beneficiary for it?
How to code this using dtm?
<div class="afgfj">
<section class="asked-questions">
<div class="g-bp-row-gutter p-comp-spacinottom p-rb">
<h2 class="p-heading-02 p-component-title">
Frequently Asked Questions
</h2>
<dl class="p-faq-main p-accordion"
data-ctn="S9031/26">
<dt class="p-top-10 p-faq-chapter p-active">
<span class="p-top-10-global">Top-10 FAQs</span>
<span class="p-top-10-local">Top 10 FAQs</span>
</dt>
<dd class="p-top-10 p-faq-list p-active">
<ul class="p-bullets">
<li class="p-faq-item" data-lang="ENG">
<div class="p-magnific-popup-launcher" data-comp-id="magnificPopupLauncher"
data-type="iframe"
data-title="Frequently asked questions"
data-close-label="Back"
data-href="//www.org.com/cgi-bin/oleeview?view=aa12_view_body.html&dct=QAD&refnr=0073544&slg=ENG&scy=GB&ctn=S9031/26">
How long does it take to get?
</div>
</li>
<li class="p-faq-item" data-lang="ENG">
<div class="p-magnific-popup-launcher" data-comp-id="magnificPopupLauncher"
data-type="iframe"
data-title="Frequently asked questions"
data-close-label="Back"
data-href="//www.org.com/cgi-bin/oleeview?view=aa12_view_body.html&dct=QAD&refnr=0020591&slg=ENG&scy=GB&ctn=S9031/26">
Can I recharge the appliance?
</div>
</li>
This is a perfect time to use an Event Based Rule. You'll also need to create a data element to hold the text value.
The main obstacle that I can see from your code would be identifying the A tag correctly.
First the Data Element: in DTM Rules, within Data Elements click Create New Data Element.
Enter a name, specify the type (CSS Selector seems the most appropriate here) then within the CSS Selector Chain list state how to reach it. My guess is for your code it would be "div.p-magnific-popup-launcher a" but you would need to test this. You can tell by opening a Inspect Element (F12) in Chrome or similar debugging gadget. There's a good blog about doing this from Adobe here.
You should also specify which part of the A tag to save. From your question you I believe you need 'text' which would capture items like "How long does it take to get?"
Under Event Based Rules within DTM click Create New Rule.
When you're happy with the settings on this page click Save Data Element.
Populate your name, and category if applicable. The Event Type should already be set to 'click'.
Within Tag you then have to set how to find the A tag through CSS, similar to above.
That's the basics, but you'll also need to set Criteria (what pages this should fire on). Furthermore, under the Adobe Analytics section you should set whether a pageview is incremented or not, and which eVars, Props and Events are populated as a result of the click. This is also where you can use the value from your Data Element. Under Link Tracking, choose Custom Link. Within Link Name, enter a percent sign (%) and your data elements should appear. Use the name you specified earlier.
Note: you should match up your populated eVars and Events etc. with your settings under Report Suites in the Analytics interface.
I am assuming you are attempting to get the text of an <a> element when it is clicked on.
Such as in the one below, you would want to get "How long does it take to get?":
How long does it take to get?
To do this, create an event based rule with the event type "click", set the element tag to "a". (See image below)
Next you will want to configure the Adobe Analytics section of the rule.
You will set the Tracking to s.tl() ,since you do not want to create a pageview when someone clicks the link (the page they view should already do that).
Then set an eVar and/or Prop to %this.text%. This is DTM notation to grab the text of the element that triggered the rule to fire.
Finally, set an event to trigger on this rule.
See image below for the configuration
This should track when an <a> element is clicked and store the text in an eVar

Adobe DTM Capturing ID from Class

I'm new to Adobe DTM so please be gentle with me! What I'm trying to do is to have a Data element hold the value of the ID of a clicked button of class "b1".
<button type="button" class="b1" id="value 1">button 1</button>
<button type="button" class="b1" id="value 2">button 2</button>
How should my Data Element be set-up since I don't want any initial value in it?
How do I structure the Event rule to capture the value of the clicked button?
I do know that I have to set the tag/selector to .b1 with event type of "click" in the condition but how do I source the "ID" value of the clicked button and assign to the Data Element.
Thanks,
Bill
Example...
Create an Event Based Rule, name it whatever you want.
Within Conditions, for the Event Type select "click".
For Element Tag or Selector put "button.b1" (no quotes). This is basically the equivalent of a css (or e.g. jQuery) selector you'd use for targeting button elements that have class "b1".
Note: You may or may not need to checkmark the Apply event handler directly to element option, depending on how your site is setup and what all is already hooked to the elements.
Now, under Rule Conditions Criteria, choose "Data > Custom" and click the "Add Criteria" button, which will then show a Custom codebox section.
Within that codebox, enter the following:
var id=this.id||'';
_satellite.setVar('b1_button_id',id);
return true;
So the way this works is that within a condition, this should be a reference to the button that was clicked. So we use that, along with DTM's _satellite.setVar() method to set a data element called "b1_button_id" to the value of the button's id attribute. Then we return true to ensure that the condition is always true, so that this condition will not prevent the rule from triggering.
From there, in any of the sections of the rule, you can reference the data element with either %b1_button_id% syntax (like in one of the form fields for setting a var through DTM) or you can use _satellite.getVar('b1_button_id') within any of the custom code blocks in the rule.
Note: data elements created on-the-fly with the .setVar() method only persist for the duration/scope of the rule being evaluated. DTM does not have an officially documented way of creating or updating persistent data elements or setting any other features that you have available from the actual Rules > Data Elements section, but there are some workarounds depending on what you want to do.
Another Note: You didn't specifically mention a need for this, but since it may be a next step that might come up.. as mentioned, within the context of a condition, this is a reference to the element for the event (in this case, the "click" event). If for some reason you need to reference this within a codebox in the Javascript / Third Pary Tags section, be aware that this will remain in context if you do NOT check the Execute Globally option, but if you DO check that option, then this will no longer be a reference to the event element.
If you need a reference to this AND you need the code to be executed globally, then you can create a data element following the instructions above, except just use this as the value, e.g.
_satellite.setVar("this_reference",this)
Then, within the codeblock you can use _satellite.getVar("this_reference") to get it.

Resources