-
How can I track hover events for multiple elements in this code?
Yo, need some help here. I nabbed this bit of code from a developer mate of mine to keep a tab on hover events over images in Google Tag Manager. Here it is:
<script> // Tracking Top Links Hover Menus function trackHoverIntent(selector, time) { var timeoutId; var elements = window.document.querySelectorAll(selector); for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('mouseenter', function(event) { var targetElement = event.target || event.srcElement; var classes = targetElement.className; var id = targetElement.id; var alt = targetElement.alt; if (!timeoutId) { timeoutId = window.setTimeout(function() { dataLayer.push({ 'event': 'gtm.hover', 'gtm.element': targetElement, 'gtm.elementClasses': classes, 'gtm.elementId': id, 'gtm.elementalt': alt, 'gtm.elementHoverTime': time }); timeoutId = null; }, time); } }); } for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('mouseleave', function() { if (timeoutId) { window.clearTimeout(timeoutId); timeoutId = null; } }); } } trackHoverIntent('img.afg-celebrate' , 1500); </script>
But there are a couple speedbumps I’ve run into:
- I got a bunch of images to track, man. But the code can only focus on tracking one at a time. Any ideas?
- Also, some pictures are shy and don’t have a class or id, just alt text. Any chance we can track those somehow, maybe by their alt text?
I’ve trawled through blogs and stuff, but no luck so far. You got any leads?
Log in to reply.