Skip to main content

useScrollTrigger

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

Submit feedback
github
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(). Hook adjusts scrolling animation with respect to the reduced-motion user preference.

Api

Hook is configured with settings object:

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

Hook returns an object with:

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

Returned scrollIntoView function accepts single optional argument alignment - optional target element alignment relatively to parent based on current axis. Default value of alignment is start.

scrollIntoView({ alignment: 'center' });

Easing

Hook accept custom easing math function to control the flow of animation. It takes t argument, which is a number between 0 and 1.

Default easing is easeInOutQuad - more info here. You can find other popular examples 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';
}) => {};
scrollStop: () => {};
};
Table of Contents