I want to implement next logic using react:
I would like to add section on my website that change the behavior of the scroll. Initially, the section is not at the top of the page so the scroll has default behavior, the page will scroll vertically. Once the section hits the top of the page, if the right part of the section is not visible, the scroll would change to make the content of the section scroll horizontally. Once the right end of the section has been reached, the default behavior of the scroll starts working as usual and the rest of the page may scroll normally. example
type I found some examples but none of them fully meets my needs. I've also tried to restrict scroll like this but it is not what i want
const targetRef = useRef(null);
const targetRef2 = useRef(null);
const [isRight, setisRight] = useState(false)
const [isLeft, setIsLeft] = useState(true)
const handleScroll = () => {
if (targetRef.current) {
const target = targetRef.current;
const viewportTop = window.scrollY;
const viewportBottom = viewportTop + window.innerHeight;
const targetTop = target.offsetTop;
const targetBottom = targetTop + target.clientHeight;
if (targetTop >= viewportTop && targetBottom <= viewportBottom && isRight) {
document.body.style.overflowY = 'hidden';
} else {
document.body.style.overflowY = 'auto';
}
}x
};
function onScroll() {
const newScrollLeft = targetRef2.current.scrollLeft
const width = targetRef2.current.clientWidth
const scrollWidth = targetRef2.current.scrollWidth
if (scrollWidth - newScrollLeft === width) {
setisRight(true);
document.body.style.overflowY = 'auto';
} else {
setisRight(false);
document.body.style.overflowY = 'hidden';
}
if (targetRef2.current.scrollLeft === 0) {
document.body.style.overflowY = 'auto';
}
}
useEffect(() => {
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return (
<div onScroll={onScroll} ref={targetRef2} style={{ height: '100vh', width: '85vw', overflowX: 'scroll' }}>
<div ref={targetRef} style={{ height: '200px', backgroundColor: 'lightblue', width: '200vw' }}>
This is the target div Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis quaerat ex, velit ratione nemo porro, tempora enim debitis deserunt commodi temporibus ab maxime, excepturi sunt iusto sapiente molestiae consequuntur voluptatem. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Illo magnam, cumque amet ab atque unde quasi repellat error soluta nihil debitis laborum quod laudantium doloremque! Inventore rerum magnam perspiciatis dolore.
</div>
</div>
);
}here