useIsTop()
useIsTop(
offset
?,element
?,debounce
?,initialValue
?):boolean
Defined in: src/hooks/dom/useIsTop.ts:62
A custom React hook to track whether a specific element (or the page) is scrolled to the top. It supports global targets (e.g., window
or document.documentElement
) and specific HTMLElement
s.
Parameters
offset?
number
= 0
The offset in pixels to consider as "top". If the scroll position is within this offset, it is considered at the top.
element?
The target element to observe scroll position. Defaults to globalThis
(commonly window
).
null
| HTMLElement
debounce?
number
= 0
The debounce delay in milliseconds for scroll and resize events. Defaults to 0
(no debounce).
initialValue?
boolean
= true
The initial value for isTop
. Defaults to true
.
Returns
boolean
isTop
- Whether the target element is currently scrolled to the top.
Examples
Example: Observing the scroll position of the page
import { useIsTop } from '@zl-asica/react';
const MyComponent = () => {
const isTop = useIsTop(50); // Consider 50px offset as top
return (
<div>
<p>{isTop ? "You're at the top!" : "Scroll up!"}</p>
<div style={{ height: '200vh', background: 'linear-gradient(to bottom, red, blue)' }} />
</div>
);
};
Example: Observing the scroll position of a specific container
import { useRef } from 'react';
import { useIsTop } from '@zl-asica/react';
const MyComponent = () => {
const containerRef = useRef<HTMLDivElement | null>(null);
const isTop = useIsTop(50, containerRef.current); // Observe a specific container
return (
<div>
<p>{isTop ? "Container is at the top!" : "Scroll up!"}</p>
<div
ref={containerRef}
style={{
height: '200px',
overflowY: 'scroll',
background: 'lightgray',
}}
>
<div style={{ height: '500px' }}>Scrollable content</div>
</div>
</div>
);
};