Can we stop animation while scrolling back to top in animate.css library

29 Views Asked by At

I am using the react-animate-on-scroll package based on the animate.css library for animating my text in web page. But I only want the animation to happen while scrolling down and not scrolling up. How can we restrict that?

 <ScrollAnimation animateIn='fadeInUp' duration={0.7}>
     <h1 className='mb-4'>Text with animation</h1>
 </ScrollAnimation>
1

There are 1 best solutions below

2
hygtfrde On

Since, react-animate-on-scroll doesn't directly provide the feature to adjust animation based on scrolling direction, unless this feature gets added, another method would be to use state variables and event listeners for scroll.

In NPM, Node.js, utilize window.pageYOffset and calculate scrollDirection as up or down based on the logic

'if the currentScrollPos is greater than the windows vertical scroll position'

or in code

currentScrollPos > (window.scrollY || window.scrollTop) ? 'down' : 'up'

The component can make use of the useEffect hook for adding and removing the event listener. window.scrollY is supported in most browsers. It represents the number of pixels that the document is currently scrolled vertically from the top. window.scrollTop is a safety check and for older browsers

import React, { useEffect, useState } from 'react';
import ScrollAnimation from 'react-animate-on-scroll';

function MyComponent() {
  const [scrollDirection, setScrollDirection] = useState('down');

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollPos = window.pageYOffset;
      const scrollDirection = currentScrollPos > (window.scrollY || window.scrollTop) ? 'down' : 'up';
      setScrollDirection(scrollDirection);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  return (
    <ScrollAnimation animateIn={scrollDirection === 'down' ? 'fadeInUp' : ''} duration={0.7}>
      <h1 className='mb-4'>Text with animation</h1>
    </ScrollAnimation>
  );
}

export default MyComponent;