useAnimateOnScroll
Hook that applies enter and leave CSS animations to elements based on viewport intersection.
Usage#
import { useAnimateOnScroll } from '@primereact/headless/animateonscroll';
const { rootProps } = useAnimateOnScroll({ enterClassName: 'fade-in' });
return <div {...rootProps}></div>;useAnimateOnScroll uses the Intersection Observer API to detect viewport entry/exit and applies CSS animation classes — see Primitive for a component-based API.
Features#
- Applies
enterClassNamewhen the element enters the viewport andleaveClassNamewhen it leaves - Configurable Intersection Observer options:
root,rootMargin,threshold oncemode to trigger the animation only on first intersection- Automatic cleanup of animation classes after
animationendandtransitionendevents
Behavior#
Enter and Leave Classes#
Set enterClassName for enter animations and leaveClassName for leave animations. Any valid CSS animation class works.
const { rootProps } = useAnimateOnScroll({
enterClassName: 'slide-in',
leaveClassName: 'fade-out'
});One-Time Animation#
Set once to animate only on the first viewport entry. After the element enters, the observer is disconnected.
const { rootProps } = useAnimateOnScroll({ enterClassName: 'fade-in', once: true });Intersection Observer Options#
Configure root, rootMargin, and threshold to control when the intersection triggers.
const { rootProps } = useAnimateOnScroll({
enterClassName: 'fade-in',
threshold: 0.8,
rootMargin: '0px 0px -100px 0px'
});threshold defaults to 0.5. Set higher values to require more of the element to be visible before triggering.
Custom Styling with Data Attributes#
The root element includes data-scope="animateonscroll" and data-part="root". During animation phases, data-enter or data-leave attributes are set on the element.
[data-scope='animateonscroll'][data-enter] {
will-change: opacity, transform;
}
[data-scope='animateonscroll'][data-leave] {
pointer-events: none;
}API#
useAnimateOnScroll#
| Name | Type | Default |
|---|---|---|
enterClassName | string | — |
| CSS class names that are applied when the element enters the viewport. | ||
leaveClassName | string | — |
| CSS class names that are applied when the element leaves the viewport. | ||
once | boolean | false |
| When enabled, animation is triggered only once. | ||
Accessibility#
See AnimateOnScroll Primitive for accessibility details.