How can I make page scrolling trigger mouseover events?

Honestly, this is gonna be a pain. You'll have to

  1. determine the size and position of every element that should get a mouseover handler.
  2. add a scroll listener to the window.
  3. In the handler, get the mouse cursor position and pageOffset.
  4. Find out which element(s) the cursor is in.
  5. manually call the actual mouseover handler
  6. (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:

  1. Add a scroll listener to the window.
  2. In the handler, call document.elementsFromPoint.
  3. Manually call the actual pointerover handler for those elements. Keep track of these elements.
  4. (optionally) Manually call the actual pointermove handler for those elements.
  5. 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;
});