I am trying to use addEventListener
when the user scroll
into view <div id="container">
. I have done so by scroll height but my attempts to addEventListener
when <div>
is on the top of the window.
handleHeaderStuck = () => {
if (this.innerContainer.scrollTop <= 500 && this.state.isStuck === true) {
this.setState({isStuck: false});
}
else if (this.innerContainer.scrollTop >= 500 && this.state.isStuck !== true) {
this.setState({isStuck: true});
}
}
This will setState
when scrolled 500px
.
How can I replace the condition of 500px
to be set when the user is with id="container"
as the top of the window? Also replace isStuck
state to isStuckBottom
when the user reaches the bottom of the div.
The full code is
constructor(props) {
super(props)
this.state = {
isStuck: false,
}
this.handleHeaderStuck = this.handleHeaderStuck.bind(this)
}
innerContainer = null
componentDidMount () {
this.innerContainer.addEventListener("scroll", this.handleHeaderStuck);
}
componentWillUnmount () {
this.innerContainer.removeEventListener("scroll", this.handleHeaderStuck);
}
handleHeaderStuck = () => {
if (this.innerContainer.scrollTop <= 500 && this.state.isStuck === true) {
this.setState({isStuck: false});
}
else if (this.innerContainer.scrollTop >= 500 && this.state.isStuck !== true) {
this.setState({isStuck: true});
}
}