Send the innerHTML content to the data layer in Tag Manager

As a newcomer to HTML and CSS, I apologize if this question has already been asked.

I am currently working on implementing tags for a new website that keeps track of the number of times sections are viewed on a page.

The section names are stored in a variable called "innerHTML" of the h2.title element. However, I'm having trouble pushing this information into the dataLayer for Tag Manager triggers.

What is the best approach for accomplishing this?

https://i.sstatic.net/OiT3P.png

https://i.sstatic.net/DQdaz.png

Answer №1

If you're looking to enhance your tracking capabilities, consider utilizing the Element Visibility Trigger Type. It can add a new layer of depth to your analysis. You can find more information about it here. However, if you prefer to stick with the Dom variable, let me provide you with an explanation of how it functions: By default, the DOM Element variable retrieves the text content of the selected element, which is similar to innerHTML in your scenario. Therefore, you can simply use this variable as a condition in the trigger setup. Allow me to illustrate this with an example: Let's say I have a tag on my page that looks like this:

<h1 id="title">test page 1</h1>
I've created a Dom element variable which returns 'test page 1'. Now, I can include this variable as a condition in my trigger for accurate tracking. Enhance your tracking capabilities by exploring these options further!

Answer №2

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The payload is properly returned by the Reducer, however, the component is receiving it as

In my current project, I am developing an application that involves fetching data from a firebase database. This particular database does not require authentication, and I have already adjusted the access rules to allow for public access. One of the actio ...

Dealing with 'this' while using an addEventListener

I need to trigger the function handleRangeUpdate in a way that it responds to the event calling it and decides whether to run console.log(this.value). The problem arises when I pass e into handleRangeUpdate using addEventListener, causing the value of thi ...

Derive the property type based on the type of another property in TypeScript

interface customFeatureType<Properties=any, State=any> { defaultState: State; properties: Properties; analyzeState: (properties: Properties, state: State) => any; } const customFeatureComponent: customFeatureType = { defaultState: { lastN ...

Error message: When accessing react-native camera roll, the message "this.state.photos is not a valid object" appears

Encountering an error while attempting to implement camera roll functionality in my demo app. The error states, "null is not an object (evaluating 'this.state.photos')" View iOS Error Message. I am a beginner developer working on my first react-n ...

Using jqgrid to customize column header tooltips which are distinct from the actual column label

From what I gather, there are multiple methods for setting distinct column header tooltips. At the moment, my approach involves using jQuery's .attr() to set the tooltips. I'm curious if there is a more streamlined way to save the custom header ...

What steps can I take to prevent encountering a Typescript Error (TS2345) within the StatePropertyAccessor of the Microsoft Bot Framework while setting a property?

During the process of constructing a bot in Typescript, I encountered TS2345 error with Typescript version 3.7.2. This error is causing issues when attempting to create properties dynamically, even if they are undefined, or referencing them in the statePro ...

Finding the second through eighth elements in a protractor using a CSS locator

Recently, I have been experimenting with protractor and facing a limitation when trying to reference elements. The only way to refer to them is through CSS, as they only have a class attribute provided. The issue arises when there are more than 7 elements ...

Updating with Setstate

Refreshing the page with Setstate, registering twice and doubling the count of both heads and tails counter every time on click instead of adding just +1 class CoinFlip extends Component { constructor(props) { super(props); ...

Unable to utilize external JavaScript files in Angular 8

I've been working on integrating an HTML template into my Angular project and for the most part, everything is going smoothly. However, I've encountered an issue where my JS plugins are not loading properly. I have double-checked the file paths i ...

Looking to bookmark Java links or a similar task?

Apologies for the lackluster title, as I am not well-versed in programming language and struggle to articulate my specific request... Allow me to explain: I frequently need to visit a particular website to conduct research (details below). I attempted usi ...

jsTree eliminates the hashtag from the URL

Utilizing a JSON generated jsTree to efficiently navigate through a directory structure has been my recent task. I have successfully implemented the select_node event to capture the path of the selected node as a string and then update the location.hash ...

Instead of logging the JSON file in the console, download it using $.getJson()

Is there a method to download a json file without using jQuery's $.getJSON() and having to log the callback function's argument? I would like to avoid manually typing it from the console.log due to its length. Is there an option to print it, eve ...

Switching on Closed Captions for HTML5 video while deactivating the standard video controls

I am facing two issues. Whenever I include the track tag in my video element, the default controller of the video pops up, which is causing conflicts with my custom controls. Secondly, I am unable to figure out how to turn closed captions on and off. Thi ...

hyperlink to choose a specific option from a drop-down menu

The challenge I am currently working on involves page1.html <a href="/foo"></a> foo.html <select ng-model="ctrl.listvalues"> <option id="{{item.value}}" ng-repeat="item" in ctrl.availableValues" value="{{item.value}}">item.di ...

Trouble Logging In: User Login Issue with SailsJS and PassportJS Plugin (sails-generate-auth)

I'm currently facing an issue with user authentication in my SailsJS app using PassportJS. I followed a tutorial on setting up authentication in SailsJS using sails-generate-auth, which can be found here. The POST request seems to be routed correctl ...

Eliminate the chosen and marked items from a list - Angular 2+/ Ionic 2

Currently, I have a checkbox list on my page. Whenever a user selects the "Save" button, the checked items should be removed from the list and moved to the saved tab that is also displayed. While I have successfully implemented the functionality for removi ...

The confusion arises from the ambiguity between the name of the module and the name of

In my current scenario, I am faced with the following issue : module SomeName { class SomeName { } var namespace = SomeName; } The problem is that when referencing SomeName, it is pointing to the class instead of the module. I have a requireme ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

Mastering the Art of Crafting an Effortless Slide Showcase

I have created a carousel that works fine except for one issue: when I reach the last image or go back from the first image, I want the image to be displayed. For example, when you click the right arrow after reaching the last image, it should show the fir ...

Code snippet for a click event in JavaScript or jQuery

I initially wrote the code in JavaScript, but if someone has a better solution in jQuery, I'm open to it. Here's the scenario: I have multiple questions with corresponding answers. I want to be able to click on a question and have its answer dis ...