useElementByPoint
useElementByPoint
is a hook that returns the element at a given point. It is useful for implementing drag and drop, or for any other use case where you need to know what element is at a given point.
Usage
Live Editor
function Demo() { const { clientX: x, clientY: y } = useMouse(); const { element, pause, resume } = useElementByPoint({ x, y }); const bounding = useElementBounding(element); useEventListener("scroll", bounding.update, null, { capture: true }); const boxStyles = (() => { if (element) { return { display: "block", width: `${bounding.width}px`, height: `${bounding.height}px`, left: `${bounding.left}px`, top: `${bounding.top}px`, backgroundColor: "#3eaf7c44", transition: "all 0.05s linear", position: "fixed", pointerEvents: "none", zIndex: 9999, border: "1px solid var(--vp-c-brand)", }; } return { display: "none", }; })(); const pointStyles = (() => ({ transform: `translate(calc(${x}px - 50%), calc(${y}px - 50%))`, position: "fixed", top: 0, left: 0, pointerEvents: "none", width: "8px", height: "8px", borderRadius: "50%", backgroundColor: "#4ade80", boxShadow: "0 0 2px rgba(0,0,0,0.3)", zIndex: 999, }))(); return ( <> <div style={boxStyles} /> <div style={pointStyles} /> <div style={{ display: "flex", alignItems: "center" }}> <span style={{ marginRight: "16px" }}>X: {x}</span> </div> <div style={{ display: "flex", alignItems: "center" }}> <span style={{ marginRight: "16px" }}>Y: {y}</span> </div> <div> <button onClick={pause}>Pause</button> <button onClick={resume}>Resume</button> </div> </> ); } render(<Demo />);
Result
Loading...
API
UseElementByPoint
Returns
UseElementByPointReturn<M>
Arguments
Argument | Description | Type | DefaultValue |
---|---|---|---|
options | options | UseElementByPointOptions<M> (Required) | - |
UseElementByPointOptions
Property | Description | Type | DefaultValue |
---|---|---|---|
x | The x coordinate of the point | number | (() => number) (Required) | - |
y | The y coordinate of the point | number | (() => number) (Required) | - |
document | The document to query | Document | null | - |
multiple | Whether to query multiple elements | M | - |
interval | The interval to query the element | number | 'requestAnimationFrame' | - |
immediate | Whether to query the element immediately | boolean | - |
UseElementByPointReturn
Property | Description | Type | DefaultValue |
---|---|---|---|
isSupported | Whether the feature is supported | boolean (Required) | - |
element | The queried element | M extends true ? Element[] : Element | null (Required) | - |
isActive | A ref indicate whether a pausable instance is active | boolean (Required) | - |
pause | Temporary pause the effect from executing | Fn (Required) | - |
resume | Resume the effects | Fn (Required) | - |
Fn
export type Fn = (this: any, ...args: any[]) => any;