How can I make page scrolling trigger mouseover events?
Honestly, this is gonna be a pain. You'll have to
- determine the size and position of every element that should get a mouseover handler.
- add a scroll listener to the window.
- In the handler, get the mouse cursor position and pageOffset.
- Find out which element(s) the cursor is in.
- manually call the actual mouseover handler
- (Find out which elements the cursor has left, if you want some mouseout behaviour too)
You may need to re-calculate the elements' positions and sizes if they are dynamic. (move 1. beneath 3.)
While this should work fine with block-level elements, I have absolutely no idea on a solution for inline elements.
This is much more simple in the modern day web using document.elementsFromPoint
:
- Add a scroll listener to the window.
- In the handler, call
document.elementsFromPoint
. - Manually call the actual
pointerover
handler for those elements. Keep track of these elements. - (optionally) Manually call the actual
pointermove
handler for those elements. - Check the list of elements from the previous time around. Manually call the actual
pointerleave
handler for elements no longer being hovered.
Here's some psuedo-code:
let prevHoveredEls = [];
document.addEventListener("scroll", (e) => {
let hoveredEls = document.elementsFromPoint(e.pageX, e.pageY);
hoveredEls = hoveredEls.filter(
(el) => el.classList.contains("elements-cared-about")
);
const notHoveredEls = prevHoveredEls.filter(
(el) => !prevHoveredEls.includes(el)
);
hoveredEls.forEach((el) => {
const bcr = el.getBoundingClientRect();
el.handlePointerEnter({
layerX: e.pageX - bcr.left,
layerY: e.pageY - bcr.top,
});
});
notHoveredEls.forEach((el) => {
const bcr = el.getBoundingClientRect();
el.handlePointerLeave({
layerX: e.pageX - bcr.left,
layerY: e.pageY - bcr.top,
});
});
prevHoveredEls = hoveredEls;
});