As the user scrolls down the page, I have a slider that smoothly slides from right to left.
What I'm trying to achieve is for the slider to fade out when the last slide is no longer in view during downward scrolling, and fade back in as the last slide re-enters the view during upward scrolling.
For a visual example of this effect, you can check out this website.
While the slider functionality is working correctly, I'm facing challenges with the smooth implementation of the fade in/fade out animations.
https://i.sstatic.net/9bjD7.png
My approach involved storing an initial opacity
value of 1
in a useRef
object
const countRefOpacity = useRef(1);
Additionally, I added a wheel
event listener to the window
useEffect(() => {
window.addEventListener("wheel", handleWheel);
return () => {
window.removeEventListener("wheel", handleWheel);
};
}, []);
The handleWheel
function is responsible for adjusting the slider opacity
based on the user's scrolling direction
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;
}
};
While the fade out animation appears smooth during downward scrolling, the fade in animation seems a bit sluggish during upward scrolling.
I'm seeking insights on how to optimize my code to achieve a seamless and natural fade in/fade out animation effect.