dev_el
dev_el

Reputation: 2947

Fading in/out scroller animation

I have a slider that slides from right to left as the user scrolls down the page.

I want the slider to fade out when the last slide is out of view when the user scrolls down, and I want the slider to fade in when the last slide is in view when the user scrolls up.

An example of what I want can be seen here

I have the slider working fine but am having trouble with the fade out/fade in animation.

enter image description here

My idea was to first store an opacity value of 1 in a useRef

const countRefOpacity = useRef(1);

And add a wheel event to my window

  useEffect(() => {
    window.addEventListener("wheel", handleWheel);
    return () => {
      window.removeEventListener("wheel", handleWheel);
    };
  }, []);

My handleWheel function decreases my slider opacity when the user scrolls down a certain point and increases the opacity when the user scrolls up a certain point

  const handleWheel = (e) => {
    if (window.scrollY >= pan.current?.offsetTop * 2 && e.deltaY > 0) {
      countRefOpacity.current = countRefOpacity.current - 0.007;
      slider.current.style.opacity = countRefOpacity.current;
    } else if (window.scrollY < pan.current?.offsetTop * 2 && e.deltaY < 0) {
      countRefOpacity.current = countRefOpacity.current + 0.007;
      slider.current.style.opacity = countRefOpacity.current;
    }
  };

I can see the fade out animation working when the user scrolls down, but the fade in animation is pretty slow when the user scrolls up.

How can I revise my code so I can make the fade in/fade out animation smooth and natural?

Codesandbox Link

Upvotes: 1

Views: 551

Answers (1)

&#198;t&#233;rnal
&#198;t&#233;rnal

Reputation: 332

If you want a CSS property to change smoothly, you can use the transition property, e.g. in your case

transition: opacity .5s;

So, assuming I understood your question correctly, I would probably use the transition property as well as add an event listener to the window's scroll event that checks whether the user has scrolled past a certain point and updates the opacity accordingly, i.e. sets it to 1 if it's before that point and to 0 otherwise. There's no need for you to calculate a delta since the transition property will handle the fade-in/fade-out for you.

Also, I believe you probably want to use scroll instead of wheel, since I think wheel only fires when you use a mouse wheel and doesn't apply to other types of scrolling.

Upvotes: 1

Related Questions