fn
useMouseInElement
v0.0.14testeddemoReactive mouse position relative to an element. Exposes the
cursor position, the cursor position relative to the element's top-left
corner, the element's position and size, and whether the cursor is outside
the element. Element geometry is observed via useElementBounding
(ResizeObserver + MutationObserver + window scroll/resize), so the
relative coordinates stay correct as the element moves or resizes — without
re-measuring the element on every pointer move.
Examples
ts
const el = useTemplateRef<HTMLElement>('el');
const { elementX, elementY, isOutside } = useMouseInElement(el);ts
// Throttle pointer reads and stop tracking outside the element
const { elementX, elementY } = useMouseInElement(el, {
handleOutside: false,
eventFilter: throttleFilter(50),
});Demo
Loading demo…
Signature
ts
export function useMouseInElement(
target?: MaybeComputedElementRef,
options: UseMouseInElementOptions ={ ... }Parameters
| Parameter | Type | Description |
|---|---|---|
target? | MaybeComputedElementRef | Element to track against. Defaults to document.body. |
options? | UseMouseInElementOptions | Options |
Returns
UseMouseInElementReturnReactive position/size refs and a stop function| Property | Type | Description |
|---|---|---|
elementX | ShallowRef<number> | Mouse X relative to the element's top-left corner |
elementY | ShallowRef<number> | Mouse Y relative to the element's top-left corner |
elementPositionX | ShallowRef<number> | The element's X position (page coordinates for type: 'page', otherwise
viewport coordinates) |
elementPositionY | ShallowRef<number> | The element's Y position (page coordinates for type: 'page', otherwise
viewport coordinates) |
elementWidth | ShallowRef<number> | The element's width |
elementHeight | ShallowRef<number> | The element's height |
isOutside | ShallowRef<boolean> | Whether the cursor is currently outside the element's bounds |
stop | () => void | Stop all tracking (mouse listeners, element observers, watchers) |