Skip to content

Instantly share code, notes, and snippets.

@jswhisperer
Created February 16, 2025 04:46
Show Gist options
  • Save jswhisperer/a2d02c0922f2bb05e72381f73489f571 to your computer and use it in GitHub Desktop.
Save jswhisperer/a2d02c0922f2bb05e72381f73489f571 to your computer and use it in GitHub Desktop.
Detect if an element is being hovered by mouse with a configurable bounding box
const el = document.querySelector("h1");
const threshold = 50;
const between = (x, min, max) => x >= min && x <= max;
const getElBoundingBox = (el, threshold = 0) => {
const elPos = el.getBoundingClientRect();
return {
top: elPos.top - threshold,
right: elPos.right + threshold,
bottom: elPos.bottom + threshold,
left: elPos.left - threshold,
};
};
const isInside = (x, y, elPos) =>
between(x, elPos.left, elPos.right) && between(y, elPos.top, elPos.bottom);
document.addEventListener("mousemove", ({ clientX, clientY }) => {
isInside(clientX, clientY, getElBoundingBox(el, threshold))
? console.log("inside")
: console.log("outside");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment