Created
February 16, 2025 04:46
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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