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

NameTypeDescription
statePositionTracks mouse position relative to the viewport and an optional element.
refReact.Ref<T>A ref to attach to a DOM element for relative position tracking.
isSupportedbooleanIndicates if the current device supports mouse position tracking.

The state object (of type Position) has the following properties:

NameTypeDescription
xnumberHorizontal position in the viewport.
ynumberVertical position in the viewport.
elementXnumberHorizontal position relative to the referenced element.
elementYnumberVertical position relative to the referenced element.
elementPositionXnumberReferenced element's horizontal position in the document.
elementPositionYnumberReferenced element's vertical position in the document.