I improved it a bit further, now it has a delay based on distance to the target.
(() => {
const ns = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(ns, "svg");
Object.assign(svg.style, {
position: "fixed",
inset: "0",
width: "100vw",
height: "100vh",
pointerEvents: "none",
zIndex: "1000",
});
const tri = document.createElementNS(ns, "polygon");
tri.setAttribute("fill", "blue");
tri.setAttribute("fill-opacity", "0.4");
tri.style.pointerEvents = "auto";
svg.append(tri);
const MIN_DELAY = 200;
const MAX_DELAY = 600;
const MS_PER_PX = 1.2;
const last = { tId: null, x: 0, y: 0, li: null, sub: null, delay: MIN_DELAY };
function clear() {
clearTimeout(last.tId);
tri.removeAttribute("points");
svg.remove();
}
function expire() {
const { x, y, li, sub } = last;
clear();
if (!li) return;
const under = document.elementFromPoint(x, y);
if (under && (li.contains(under) || sub?.contains(under))) return;
const init = { bubbles: true, cancelable: true, view: window, clientX: x, clientY: y, relatedTarget: under };
//notify li that we are out
li.dispatchEvent(new MouseEvent("mouseout", init));
li.dispatchEvent(new MouseEvent("mouseleave", { ...init, bubbles: false }));
//notifiy new target that we are hovering
if (under) {
under.dispatchEvent(new MouseEvent("mouseover", { ...init, relatedTarget: li }));
under.dispatchEvent(new MouseEvent("mousemove", init));
}
}
document.addEventListener(
"mousemove",
(e) => {
if (e.target === tri) {
last.x = e.clientX;
last.y = e.clientY;
clearTimeout(last.tId);
last.tId = setTimeout(expire, last.delay);
return;
}
const li = e.target.closest?.("li.red-ui-menu-dropdown-submenu");
if (!li) return clear();
const anchorId = li.querySelector(":scope > a")?.id;
const subMenu = anchorId && document.getElementById(anchorId + "-submenu");
if (!subMenu) return clear();
if (subMenu.contains(e.target)) return clear();
const r = subMenu.getBoundingClientRect();
if (!r.width || !r.height) return clear();
last.x = e.clientX;
last.y = e.clientY;
last.li = li;
last.sub = subMenu;
const x = e.clientX < r.left ? r.left : r.right;
tri.setAttribute("points", `${x},${r.top},${x},${r.bottom},${e.clientX},${e.clientY}`);
//compute the delay based on largest distance to submenu
const d = Math.max(Math.hypot(x - e.clientX, r.top - e.clientY), Math.hypot(x - e.clientX, r.bottom - e.clientY));
last.delay = Math.max(MIN_DELAY, Math.min(d * MS_PER_PX, MAX_DELAY));
if (svg.parentElement !== li) li.append(svg);
},
true,
);
})();