useScrollPosition()
useScrollPosition(
element?,percentage?,debounce?,initialValue?):number
Defined in: hooks/dom/useScrollPosition.ts:96
A custom React hook to track the vertical scroll position of a specific element or the window. Automatically updates whenever the user scrolls.
Parameters
element?
The target element to track. Defaults to globalThis (window scroll position).
typeof globalThis | HTMLElement
percentage?
boolean = false
Whether to return the scroll position as a percentage.
debounce?
number = 0
The debounce delay in milliseconds for the scroll event.
initialValue?
number = 0
The initial scroll position value, used when the DOM is not available.
Returns
number
The current vertical scroll position (in pixels or percentage).
Examples
// Tracking the scroll position of the page
import { useScrollPosition } from '@zl-asica/react';
const MyComponent = () => {
const scrollPosition = useScrollPosition();
return <div>Scroll Position: {scrollPosition}</div>;
};// Tracking the scroll position of a specific container
import { useRef } from 'react';
import { useScrollPosition } from '@zl-asica/react';
const MyComponent = () => {
const containerRef = useRef<HTMLDivElement | null>(null);
const scrollPosition = useScrollPosition(containerRef.current);
return (
<div ref={containerRef} style={{ height: '200px', overflowY: 'scroll' }}>
<div style={{ height: '500px' }}>Content</div>
<div>Scroll Position: {scrollPosition}</div>
</div>
);
};