I've got an SVG map made up of hexagons which are divided up into groups. When the user hovers over a group, I'd like to have a tooltip appear. Thing is, I want there to be like a 3 second delay to this tooltip. So if the user decides to hover off during that delay, I'd like to clear that delay to stop the tooltip from appearing as they are no longer hovering over it. There is also a delay for when the tooltip disappears as well just in case you hover over another element after quickly moving off the previous one.
I'm using setTimeout for this. What I've done here works 50% of the time but I'm finding that if I hover over and let the tooltip display, and then quickly hover over a bunch of other different elements before hovering off, the tooltip will disappear but then quickly reappear again.
Here's my code, am happy to explain anything further if needed. Cheers!
// Setting the tooltip to appear below the tooltip wrapper
gsap.set(tip, {
yPercent: 100
});
// Tooltip Hovering Functionality with Timeouts
let hoverOutTimeout; // Timeout for hovering out
// GO through grouped elements with an event listener on mouse move, and use timeouts to delay hover
for (i = 0; i < lgas.length; i++) {
lgas[i].onmouseover = function () {
if (hoverOutTimeout) { // Check to see if the delay for the mouseleave function is running
clearTimeout(hoverOutTimeout);
//console.log("Hover back in");
} else {
//console.log("Hovering in");
}
// Set 3s delay to display tooltip
hoverTimeout = setTimeout(function () {
//console.log("Hovered in");
gsap.to(tip, {
yPercent: 0,
ease: 'bounce.out'
});
}, 3000);
}
lgas[i].onmouseleave = function () {
if (hoverTimeout) { // If delay to show tooltip is running, clear it
clearTimeout(hoverTimeout);
//console.log("Hovering back out")
hoverOutTimeout = setTimeout(() => { // Start new delay to hide tooltip
//console.log("Hovered out");
gsap.to(tip, {
yPercent: 100,
ease: 'back.in'
});
}, 2000);
}
clearTimeout(hoverTimeout);
}
}