useMouse
Tracks pointer coordinates relative to the page and an element.
Tracks pointer coordinates relative to the page and an element.
Import
import { useMouse } from '@kamod-ch/hooks'Live demo
Basic demo
Tracks pointer coordinates relative to the page and an element.
Browser-only demo
This demo starts after the page mounts in the browser.
import { useRef } from 'preact/hooks'
import { useMouse } from '@kamod-ch/hooks'
export default function UseMouseDemo() {
const ref = useRef<HTMLDivElement>(null)
const mouse = useMouse(ref)
return (
<div>
<div ref={ref} class="demo-target-box demo-large-box">Move the pointer here.</div>
<p><strong>Element coordinates:</strong> {Math.round(mouse.elementX)}, {Math.round(mouse.elementY)}</p>
</div>
)
}
API
TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
export interface CursorState {
screenX: number;
screenY: number;
clientX: number;
clientY: number;
pageX: number;
pageY: number;
elementX: number;
elementY: number;
elementH: number;
elementW: number;
elementPosX: number;
elementPosY: number;
}
declare const _default: (target?: BasicTarget) => CursorState;
export default _default;
/SSR considerations
This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.
Browser compatibility
Requires the corresponding browser API to exist in the current environment.