Skip to content

useMouse

Track cursor position

Code demonstration

Default Usage

Client - x: NaN, y: NaN

Page - x: NaN, y: NaN

Screen - x: NaN, y: NaN

Default UsageTracking cursor position.

Mouse position relative to the element

element

Mouse In Element - x: NaN, y: NaN

Element Position - x: NaN, y: NaN

Element Dimensions - width: NaN, height: NaN

Mouse position relative to the elementBy passing in the target element, you can get the position of the mouse relative to the element.

API

typescript
const state: {
  screenX: number,
  screenY: number,
  clientX: number,
  clientY: number,
  pageX: number,
  pageY: number,
  elementX: number,
  elementY: number,
  elementH: number,
  elementW: number,
  elementPosX: number,
  elementPosY: number,
} = useMouse(target?: Target);

Params

PropertyDescriptionType
targetDOM element or refElement | () => Element | JSX.Element

Result

PropertyDescriptionType
screenXPosition left relative to the top left of the physical screen/monitornumber
screenYPosition top relative to the top left of the physical screen/monitornumber
clientXPosition left relative to the upper left edge of the content areanumber
clientYPosition top relative to the upper left edge of the content areanumber
pageXPosition left relative to the top left of the fully rendered content area in the browsernumber
pageYPosition top relative to the top left of the fully rendered content area in the browsernumber
elementXPosition left relative to the upper left edge of the target elementnumber
elementYPosition top relative to the upper left edge of the target elementnumber
elementHTarget element heightnumber
elementWTarget element widthnumber
elementPosXThe position of the target element left relative to the top left of the fully rendered content area in the browsernumber
elementPosYThe position of the target element top relative to the top left of the fully rendered content area in the browsernumber

Source

Source · Document · Demo

Released under the MIT License.