To incorporate this JavaScript snippet into your webpage, simply include it within your page's 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 script adds the title information to the dataLayer under the key "sectionTitle" if the section title is visible on the user's screen.
Afterward, you can retrieve and use this data from the dataLayer in Google Tag Manager by setting up appropriate tags and triggers.