I have created an SVG map consisting of hexagons grouped together. My goal is to display a tooltip when the user hovers over a group, but with a 3-second delay. If the user moves away before the delay ends, I want to clear that delay to prevent the tooltip from showing. There is also a delay for the tooltip to disappear in case the user quickly moves to another element after hovering.
My current approach involves using setTimeout for this functionality. While it works most of the time, I have noticed that if I rapidly hover over different elements, the tooltip may reappear unexpectedly.
Below is my code snippet. Feel free to ask if you need further explanation. Thank you!
// Positioning the tooltip below the tooltip wrapper
gsap.set(tip, {
yPercent: 100
});
// Implementing Tooltip Hover Behavior with Timeouts
let hoverOutTimeout; // Timeout for mouseleave event
// Adding event listener on mouse move to group elements and using timeouts to control hover behavior
for (i = 0; i < lgas.length; i++) {
lgas[i].onmouseover = function () {
if (hoverOutTimeout) {
clearTimeout(hoverOutTimeout);
} else {
}
hoverTimeout = setTimeout(function () {
gsap.to(tip, {
yPercent: 0,
ease: 'bounce.out'
});
}, 3000);
}
lgas[i].onmouseleave = function () {
if (hoverTimeout) {
clearTimeout(hoverTimeout);
hoverOutTimeout = setTimeout(() => {
gsap.to(tip, {
yPercent: 100,
ease: 'back.in'
});
}, 2000);
}
clearTimeout(hoverTimeout);
}
}