Reputation: 449
I am new to HTML and CSS so sorry if this has been posted before.
I am building tags for a new website that tracks the number of times sections on a page have been viewed.
The names of the sections are contained in a variable called "innerHTML" of the h2.title. I can't seem to push this into the dataLayer for Tag Manager to use in triggers.
How do I go about this?
Upvotes: 1
Views: 3007
Reputation: 3847
Consider using Element Visibility Trigger Type
https://support.google.com/tagmanager/answer/6106961#element_visibility
If you'd like to stuck with Dom variable here is some explanation of how it works:
By default the DOM Element variable returns the text content of selected element. That seems to be the same as innerHTML in your case.
So you may just use this variable as the condition in the trigger.
Here is an example.
I have a tag on my page
<h1 id="title">test page 1</h1>
and I created a DOM element variable
This variable resolves to 'test page 1'
Now I can use this as a condition in my trigger
Upvotes: 1
Reputation: 8736
You can add this Javascript code in your page HTML.
window.dataLayer = window.dataLayer || [];
window.addEventListener('scroll', function() {
var sections = document.querySelectorAll('h2.title');
for(i=0;i<sections.length;i++)
{
if (checkVisible(sections[i])) {
var sectionTitle = sections[i].innerText;
if(dataLayer.length == 0 || dataLayer[dataLayer.length-1]["sectionTitle"] != sectionTitle){
dataLayer.push({"sectionTitle":sectionTitle });
}
}
}
});
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
This code is pushing title to dataLayer with key "sectionTitle" if section title is visible in the users screen.
Then you can read datalayer in GTM and setup propper tags/triggers
Upvotes: 0