2025-04-16 16:13:31 +02:00

87 lines
2.9 KiB
JavaScript

/**
* Palantics class-based tracking script
*/
document.addEventListener('DOMContentLoaded', function() {
// Helper function to get element details for tracking
function getElementDetails(element) {
const details = {};
// Get element text or alternative
if (element.textContent && element.textContent.trim()) {
details.text = element.textContent.trim();
} else if (element.placeholder) {
details.text = element.placeholder;
} else if (element.value) {
details.text = element.value;
} else if (element.alt) {
details.text = element.alt;
} else if (element.getAttribute('aria-label')) {
details.text = element.getAttribute('aria-label');
}
// Limit text length
if (details.text && details.text.length > 50) {
details.text = details.text.substring(0, 47) + '...';
}
// Get element ID, class and href if available
if (element.id) {
details.id = element.id;
}
if (element.className) {
details.class = element.className;
}
if (element.href) {
const href = element.href;
// Only include if it's not too long
if (href.length < 100) {
details.href = href;
}
}
return details;
}
// Function to initialize tracking for a specific class
function initializeClassTracking(className) {
const elements = document.querySelectorAll('.' + className);
elements.forEach(function(element) {
element.addEventListener('click', function(e) {
const details = getElementDetails(element);
tE('custom_element_click', {
element: 'custom',
class: className,
...details
});
});
});
}
// Track elements with data-track attribute
function initializeDataAttributeTracking() {
const trackedElements = document.querySelectorAll('[data-track]');
trackedElements.forEach(function(element) {
element.addEventListener('click', function(e) {
const eventName = element.getAttribute('data-track') || 'tracked_element';
const details = getElementDetails(element);
tE(eventName, {
element: 'data-track',
...details
});
});
});
}
// Initialize data attribute tracking
initializeDataAttributeTracking();
// If trackClasses is defined (will be injected by WordPress), initialize class tracking
if (typeof trackClasses !== 'undefined' && Array.isArray(trackClasses)) {
trackClasses.forEach(function(className) {
initializeClassTracking(className);
});
}
});