MCPcopy Create free account
hub / github.com/danielpetho/fancy / useMousePosition

Function useMousePosition

src/hooks/use-mouse-position.ts:3–42  ·  view source on GitHub ↗
(
  containerRef?: RefObject<HTMLElement | SVGElement | null>
)

Source from the content-addressed store, hash-verified

1import { RefObject, useEffect, useState } from "react"
2
3export const useMousePosition = (
4 containerRef?: RefObject<HTMLElement | SVGElement | null>
5) => {
6 const [position, setPosition] = useState({ x: 0, y: 0 })
7
8 useEffect(() => {
9 const updatePosition = (x: number, y: number) => {
10 if (containerRef && containerRef.current) {
11 const rect = containerRef.current.getBoundingClientRect()
12 const relativeX = x - rect.left
13 const relativeY = y - rect.top
14
15 // Calculate relative position even when outside the container
16 setPosition({ x: relativeX, y: relativeY })
17 } else {
18 setPosition({ x, y })
19 }
20 }
21
22 const handleMouseMove = (ev: MouseEvent) => {
23 updatePosition(ev.clientX, ev.clientY)
24 }
25
26 const handleTouchMove = (ev: TouchEvent) => {
27 const touch = ev.touches[0]
28 updatePosition(touch.clientX, touch.clientY)
29 }
30
31 // Listen for both mouse and touch events
32 window.addEventListener("mousemove", handleMouseMove)
33 window.addEventListener("touchmove", handleTouchMove)
34
35 return () => {
36 window.removeEventListener("mousemove", handleMouseMove)
37 window.removeEventListener("touchmove", handleTouchMove)
38 }
39 }, [containerRef])
40
41 return position
42}

Callers 3

PixelateSVGFilterDemoFunction · 0.90
PreviewFunction · 0.90
useElasticLineEventsFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected