I am changing the background-color of my navbar on scroll event, it works, but the problem is that the function changeNavBar
is triggered on every scroll movement. I'd like to know how can I make it be triggered only at a certain point of the screen.
For instance, let's say the function should be called only when the YPosition is bigger than 50, once it is called it wouldn't be called again, unless the screen is scrolled up and the navbar reaches a point smaller than 50. In other words, we start at 0, it reaches 50 it is called, but it isn't called if the screen keeps being scrolled down, it won't be called it YPosition is 100, 200, 1000, doesn't matter. But if the page is scrolled up and reaches 50'inch it will be called.
This is my code:
const Navigation = props => {
let [navBg, setNavBg] = React.useState('transparent')
let navbarStyle = {
backgroundColor: navBg
}
const changeNavBar = () => {
if (window.scrollY > 50) {
setNavBg('blue')
} else {
setNavBg('transparent')
}
console.log('test')
}
React.useEffect(() => {
window.addEventListener('scroll', changeNavBar);
return () =>
window.removeEventListener('scroll', changeNavBar);
}, []);
return (
<div style={navbarStyle}>
<Logo />
<MenuNavigation />
</div>
)
}
The issue is not what happens within the function changeNavBar
. What I want is to prevent the function to be called when it is not necessary.