"Utilizing Google Tag Manager to trigger events and push them to the data layer

My goal with this code is to trigger an event in the data layer through Google Tag Manager whenever a user hovers over a specific area on the website for at least 1 second. The challenge I'm facing is that I have 8 other areas on the site using the same code, each pushing different information to the data layer (with distinct IDs). However, all these areas end up triggering the same event upon hover (the last event set up as a Tag in Google Tag Manager).

How can I ensure that these events are pushed correctly to the data layer?

Thank you, Attila

Below are two examples of the code:

var startTime; var endTime; var differenceTime;

document.getElementById("budapest-pin").onmouseover = function() {mouseOver()};
document.getElementById("budapest-pin").onmouseout = function() {mouseOut()};

function mouseOver() {
    startTime = Date.now();
};

function mouseOut() {
    endTime = Date.now();
    differenceTime = (endTime - startTime) / 1000;
    
    if (differenceTime > 1){
        dataLayer.push({'event': 'budapest'});
    };
};
</script>
<script>
var startTime; var endTime; var differenceTime;

document.getElementById("szeged-pin").onmouseover = function() {mouseOver()};
document.getElementById("szeged-pin").onmouseout = function() {mouseOut()};

function mouseOver() {
    startTime = Date.now();
};

function mouseOut() {
    endTime = Date.now();
    differenceTime = (endTime - startTime) / 1000;

    if (differenceTime > 1){
        dataLayer.push({'event': 'szeged'});
    };
};
</script>

Answer №1

To add listening events to your page, use the code below:

var startTime = {};
var endTime = {};
document.getElementById("budapest-pin").onmouseover = function() {
    mouseOver('budapest')
};
document.getElementById("budapest-pin").onmouseout = function() {
    mouseOut('budapest')
};
document.getElementById("szeged-pin").onmouseover = function() {
    mouseOver('szeged')
};
document.getElementById("szeged-pin").onmouseout = function() {
    mouseOut('szeged')
};

function mouseOver(id) {
    startTime[id] = Date.now();
};

function mouseOut(id) {
    endTime[id] = Date.now();
    var differenceTime = (endTime[id] - startTime[id]) / 1000;
    if (differenceTime > 1) {
        dataLayer.push({
            'event': 'mytaghover',
            'eventCategory': id,
            'eventAction': 'hover',
            'eventLabel': 'hovered ' + differenceTime + ' seconds'
        });
    };
}; 

Follow these steps in GTM:

  1. Create 3 GTM variables with the type 'Data Layer Variable' and the following titles and data layer variable names:

    • dataLayer Category - eventCategory
    • dataLayer Action - eventAction
    • dataLayer Label - eventLabel
  2. Create a GTM trigger titled MyHover trigger, with type 'Custom event', and set the 'Event name' as mytaghover

  3. Create a GTM tag with the type 'Google Analytics'. Enter your 'Tracking ID'. Choose 'event' in the 'Track Type' field. Fill in the 'Event Tracking Parameters' fields with the appropriate variables from step 1. Under 'Fire On', select 'More' and choose MyHover trigger as the trigger.

  4. Test your container in 'Preview' mode before publishing it.

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

Glitch found in Safari involving innerText of elements

Hey everyone, I posted this question not too long ago but now I have some images to share regarding the issue with Safari. When checking the console in Safari, the following text is displayed: <div id="rot3posDisp" class="rotDisp">C</div> Ho ...

What's the reason behind beforeunload not triggering?

I've gone through numerous similar posts, but I'm struggling to figure out what's not quite right with this code snippet: $(window).on("beforeunload", function () { debugger handleBeforeUnload(); return false; }); function handl ...

The button on my VUE 3 quiz app is not changing to 'Finish' when I reach the final question

Struggling with my Vue 3 quiz app - everything works perfectly until I reach the last question. The button text should change to 'Finish' once the final question is loaded. Despite hours of searching and even using copilot, I still can't fin ...

Rendering React Js component occurs just once following a state update

My journey with ReactJS is just beginning, and I'm facing an unusual issue which might be due to my unconventional implementation approach. Previously, everything was working smoothly. However, when I tried to introduce new features, things started g ...

Sorry, but we're unable to provide a unique rewrite of text that is an original error message

Trying to fetch data from a MySQL database using Next.js API routes, I encountered the following error: Error: No response returned from the route handler Below is an example of the code being used: import { NextResponse } from "next/server"; impor ...

Javascript challenges for beginners in coding world

After running the code snippet, I encountered the following error messages: at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Fun ...

Experiencing difficulties with JWT implementation and seeking to transmit the JWT token to additional APIs

I am currently working on implementing JWT authentication in node js/express js: Below is the sample code I have written for this purpose: const jwt = require('jsonwebtoken'); const secretKey = crypto.randomBytes(64).toString('hex'); c ...

Issue with HTML form not correctly submitting AJAX request to controller

My attempt to utilize ajax on the add to cart form doesn't seem to be working as expected. When I click on the Add to Cart button, it displays a blank page because I have implemented an ajax check method in the controller. Controller public functio ...

Utilize Javascript to establish a fresh attribute by analyzing other attributes contained in an array within the object

Currently, I am working on a data structure that looks like this: masterObject: { Steps: [ { step: { required: false, }, step: { required: false, }, step: { required: false, }, }, ] } ...

Struggling to log the values emitted from socket.io and express-nodejs

Having an issue with socket.io where the code is not emitting a value on a specific route. It works fine on the '/' route, but once I click submit and the route changes to '/process_post', I am unable to catch the emitted values by sock ...

Can we create a collection of Vue highcharts components in a library format?

I am in search of an answer, with hope that it lies here. I have used the following: "vite": "^2.7.13", "highcharts": "^9.3.3", "highcharts-vue": "^1.4.0" I aim to create a library of Vue compon ...

Stopping the execution of jQuery().load()

The .load() feature in the jQuery library allows users to selectively load elements from another page, based on specific criteria. I am curious to know if it's feasible to stop or cancel the loading process once initiated. In our program, users can e ...

What are the steps to set up mocha to automatically monitor source or project files?

Is there a way for Mocha to only watch my source/project files and not the test files? The test files and source/project files are located in separate directories. Any help or guidance would be greatly appreciated. Thank you! ...

After installing grunt, the Gruntfile cannot be located. How can this issue be resolved?

After installing grunt, I encountered a problem. Despite trying some commands suggested on stackoverflow in this How to install grunt and how to build script with it, running the grunt command still shows the same result. What steps should I take next?ht ...

How can I send various maximum values to the Backbone template?

Although in theory, it may seem simple, I am unsure about the exact code to use. In a view, if I define a variable max that retrieves an attribute called points from a collection, I can pass this variable as an object into my template using maxPoints.toJS ...

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

TypeScript multi-dimensional array type declaration

I currently have an array that looks like this: handlers: string[][] For example, it contains: [["click", "inc"], ["mousedown", "dec"]] Now, I want to restructure it to look like this: [[{ handler: "click" ...

Creating an array object in TypeScript is a straightforward process

Working on an Angular 4 project, I am attempting to declare an attribute in a component class that is an object containing multiple arrays, structured like this: history: { Movies: Array<Media>, Images: Array<Media>, Music: Array<Medi ...