Track Single Section
Reveal Effect

Creating a reveal effect on a webpage can significantly enhance user engagement and provide a dynamic browsing experience. The useIntersectionReveal() hook can be employed to detect when an element enters the viewport and trigger animations or transitions.

It can be integrated with CSS animations or JavaScript libraries such as react-spring or framer-motion to animate text, images, or other elements as they come into view, making the content more interactive and visually appealing.

Usage

useIntersectionReveal(sectionRef, trackOnce, options) gives you the ability to track whether the element (tracked with sectionRef) enters the viewport. It takes two arguments:

  • sectionRef: A reference to the element to observe.
  • trackOnce: A boolean that determines whether to observe the element only once. Default value: false.
  • options: Allow customizing the observer. You can pass an IntersectionObserverOptions object to configure the observer (opens in a new tab).
  import { useIntersectionReveal } from '@react-scrollytelling/core';
 
  // inside a React component
  const trackOnce = true;
  const sectionRef = useRef<HTMLDivElement>(null);
  const { isIntersecting } = useIntersectionReveal(sectionRef, trackOnce);
 
  return (
    <div
      ref={sectionRef}
      style={{
        opacity: isIntersecting ? 1 : 0,
        transform: isIntersecting ? 'translateY(0)' : 'translateY(10px)',
      }}
    >
      Play animation when it enters the viewport
    </div>
  );

Example

Reveal multiple times

trackOnce is false by default, which means that we want to trigger the animation every time the element enters the viewport:

Loremipsumdolorsit
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Reveal once

trackOnce is true, which means that we want to trigger the animation only once when the element enters the viewport. This is a very common use case for product page animations/lazy loading images:

Loremipsumdolorsit
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Behind the scenes

useIntersectionReveal() hook is a simple wrapper around the useIntersectionObserver() hook, which uses the Intersection Observer API (opens in a new tab) to detect when an element enters the viewport, and changes the isIntersecting state accordingly, and disconnect the observer when trackOnce is true and the element is already in view.