Docs
useMousePosition
Use the useCopyToClipboard hook to copy text to the clipboard and track whether the copy action was successful, with an optional delay to reset the copied state.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-mouse-position
Usage
"use client"
import React from "react"
import { useMousePosition } from "@/hooks/useMousePosition"
export default function App() {
const { position, ref, isSupported } = useMousePosition<HTMLDivElement>()
if (!isSupported) {
return <p>Mouse position tracking is not supported in this device.</p>
}
return (
<div>
<div
ref={ref}
style={{
width: "300px",
height: "300px",
background: "lightgray",
position: "relative",
}}
>
<p>
Mouse position inside element: {position.elementX},{" "}
{position.elementY}
</p>
</div>
<p>
Mouse position in viewport: {position.x}, {position.y}
</p>
</div>
)
}
API Reference
Return Values
Name | Type | Description |
---|---|---|
state | Position | Tracks mouse position relative to the viewport and an optional element. |
ref | React.Ref<T> | A ref to attach to a DOM element for relative position tracking. |
isSupported | boolean | Indicates if the current device supports mouse position tracking. |
The state
object (of type Position
) has the following properties:
Name | Type | Description |
---|---|---|
x | number | Horizontal position in the viewport. |
y | number | Vertical position in the viewport. |
elementX | number | Horizontal position relative to the referenced element. |
elementY | number | Vertical position relative to the referenced element. |
elementPositionX | number | Referenced element's horizontal position in the document. |
elementPositionY | number | Referenced element's vertical position in the document. |