fn

useMouseInElement

v0.0.14testeddemo

Reactive 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

ParameterTypeDescription
target?MaybeComputedElementRefElement to track against. Defaults to document.body.
options?UseMouseInElementOptionsOptions

Returns

UseMouseInElementReturnReactive position/size refs and a stop function
PropertyTypeDescription
elementXShallowRef<number>Mouse X relative to the element's top-left corner
elementYShallowRef<number>Mouse Y relative to the element's top-left corner
elementPositionXShallowRef<number>The element's X position (page coordinates for type: 'page', otherwise viewport coordinates)
elementPositionYShallowRef<number>The element's Y position (page coordinates for type: 'page', otherwise viewport coordinates)
elementWidthShallowRef<number>The element's width
elementHeightShallowRef<number>The element's height
isOutsideShallowRef<boolean>Whether the cursor is currently outside the element's bounds
stop() => voidStop all tracking (mouse listeners, element observers, watchers)