Skip to main content

useScrollTrigger

The useScrollTrigger is a custom hook for handling scroll behavior for any scrollable element.

github
View source code
import { useScrollTrigger } from '@uhg-abyss/web/hooks/useScrollTrigger';

Usage

useScrollTrigger handles scroll behavior for any scrollable element. Basic usage works the same way as element.scrollIntoView(). The hook adjusts the scrolling animation with respect to the prefers-reduced-motion user preference.

API

The hook is configured with a settings object:

  • onScrollFinish - callback function executed after the scroll animation
  • easing - a custom math easing function
  • duration - duration of the scroll animation in milliseconds, default is 1250
  • axis - the axis of scroll, default is y
  • cancelable - indicates whether the animation may be interrupted by user scrolling. Default is true
  • offset - additional distance between the nearest edge and element. Default is 0
  • isList - a flag that prevents content jumping in scrolling lists with multiple targets, e.g. Select, Carousel. Default is false

The hook returns an object with:

  • scrollIntoView - function that starts the scroll animation
  • scrollStop - function that stops the scroll animation
  • targetRef - ref of the target HTML node
  • scrollableRef - ref of the scrollable parent HTML element. If not used, the document element will be used

The returned scrollIntoView function accepts a single optional argument alignment, which is the alignment of the target element relative to the parent based on the current axis. The default value of alignment is 'start'.

scrollIntoView({ alignment: 'center' });

Easing

Use the easing parameter to control the timing of the animation. It accepts a function that takes a single argument t which is a number between 0 and 1 representing the progress of the animation.

Info

The default easing function is easeInOutQuad. Learn more about different easing functions on easings.net.

// Default value of easeInOutQuad
useScrollTrigger({
easing: (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),
});

Parent node

Scroll X axis

Drawer

ModalDialog

Properties

useScrollTrigger({
onScrollFinish?: () => {},
duration?: number,
axis?: 'x' | 'y',
easing?: (t: number) => number,
offset?: number,
cancelable?: boolean,
isList?: boolean,
sRef?: MutableRefObject,
tRef?: MutableRefObject,
}): {
targetRef: MutableRefObject,
scrollableRef: MutableRefObject,
scrollIntoView: ({
alignment?: 'start' | 'end' | 'center',
}) => void,
scrollStop: () => void,
};
Table of Contents