useScroll
Reads scroll position from an element or document.
Reads scroll position from an element or document.
Import
import { useScroll } from '@kamod-ch/hooks'Live demo
Basic demo
Reads scroll position from an element or document.
Browser-only demo
This demo starts after the page mounts in the browser.
import { useRef } from 'preact/hooks'
import { useScroll } from '@kamod-ch/hooks'
export default function UseScrollDemo() {
const ref = useRef<HTMLDivElement>(null)
const position = useScroll(ref)
return (
<div>
<div ref={ref} class="demo-scroll-box">{Array.from({ length: 20 }, (_, index) => <p key={index}>Scrollable row {index + 1}</p>)}</div>
<p><strong>Top:</strong> {position?.top ?? 0}</p>
</div>
)
}
API
TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
type Position = {
left: number;
top: number;
};
export type Target = BasicTarget<Element | Document>;
export type ScrollListenController = (val: Position) => boolean;
declare function useScroll(target?: Target, shouldUpdate?: ScrollListenController): Position | undefined;
export default useScroll;
/SSR considerations
This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.
Browser compatibility
Requires the corresponding browser API to exist in the current environment.