document.addEventListener('DOMContentLoaded', function () { // Find all elements that have the 'showtooltip' attribute const elementsWithTooltip = document.querySelectorAll('[showtooltip]'); let tooltipInstance = null; // To hold the reference to the currently visible tooltip elementsWithTooltip.forEach(element => { // Event listener for when the mouse enters the element's area element.addEventListener('mouseenter', function () { const tooltipText = element.getAttribute('showtooltip'); // Don't do anything if the attribute is empty if (!tooltipText) { return; } // 1. Create the tooltip element tooltipInstance = document.createElement('div'); tooltipInstance.className = 'tooltip'; tooltipInstance.textContent = tooltipText; // 2. Add it to the document body document.body.appendChild(tooltipInstance); // 3. Calculate position const elementRect = element.getBoundingClientRect(); const tooltipRect = tooltipInstance.getBoundingClientRect(); // Position it above and centered relative to the element // We add window.scrollY to account for page scrolling const top = elementRect.top + window.scrollY - tooltipRect.height - 8; // 8px gap const left = elementRect.left + window.scrollX + (elementRect.width / 2) - (tooltipRect.width / 2); tooltipInstance.style.top = `${top}px`; tooltipInstance.style.left = `${left}px`; // Fade it in by setting opacity to 1 // A small timeout ensures the transition effect works correctly setTimeout(() => { if (tooltipInstance) { tooltipInstance.style.opacity = '1'; } }, 10); }); // Event listener for when the mouse leaves the element's area element.addEventListener('mouseleave', function () { // If a tooltip exists, remove it if (tooltipInstance) { tooltipInstance.remove(); tooltipInstance = null; } }); }); });