I recently had this issue with the Navbar code in ReactJS to give the Navbar a background color after scrolling 100px on the y-axis and remove it if the page view is within 100px of the top.
All I had to do is introduce a reverse function in the removeEventListener to give it the rules for application.
const [show, handleShow] = useState(false);
useEffect(() => {
window.addEventListener('scroll', () => {
if (window.scrollY > 100) {
// do this
handleShow(true);
} else handleShow(false);
});
return () => {
window.removeEventListener('scroll', () => {
if (window.scrollY < 100) {
// do this
handleShow(false);
} else handleShow(true);
});
};
});