How ChatGPT Helped Me Push a DataLayer Event for GTM ??
Ever found yourself stuck trying to track specific actions or information on your website, only to find it’s not available in the existing dataLayer or GTM variables? And, of course, the dev team is either swamped or unavailable. ??
Well, here’s a use case that might just save the day!
Here’s how ChatGPT made it easy:
Here’s the simple script ChatGPT helped me create:
领英推荐
// Select all elements with the class 'wedocs-doc-link'
var docLinks = document.querySelectorAll('.wedocs-doc-link a');
// Loop through each element and add a click event listener
docLinks.forEach(function(link) {
link.addEventListener('click', function(event) {
// Prevent the default action (optional)
event.preventDefault();
// Find the parent li element
var parentLi = link.closest('.wedocs-docs-single');
// Retrieve the text of the h3 element within the same li
var headerText = parentLi.querySelector('h3 a').innerText;
// Push the event to the dataLayer
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
'event': 'docLinkClick',
'headerText': headerText
});
// Log the dataLayer for testing purposes
console.log('Event pushed to dataLayer:', {
'event': 'docLinkClick',
'headerText': headerText
});
// Optionally, you can still follow the link after pushing the event
// window.location.href = link.href;
});
});
To make it even clearer, Here's a quick video showing how I added the code to the console and demonstrating the dataLayer event in action. ??
If you're not a JavaScript expert but need to track specific actions or information on your website without waiting for your dev team, give ChatGPT a try. It’s like having a coding assistant right there with you! ??
Senior Managing Director
4 个月Ahmed Mostafa Very insightful. Thank you for sharing