I have a div that has scrolling enabled for that div. I have some elements in it, when the user starts to scroll I want an element to disappear and when scrolling stops I want it to show up again.
How can I do this
JavaScript
x
18
18
1
<div className="container"/>
2
<div>Hide me on scrolling</div>
3
<div>Always show </div>
4
</div>
5
6
.container{
7
flex: 1 1 80%;
8
display: flex;
9
flex-wrap: wrap;
10
width: calc(100vw - 110px);
11
height: calc(100vh - 75px);
12
overflow-y: auto;
13
min-width: 500px;
14
display: flex;
15
justify-content: center;
16
z-index: 1;
17
}
18
Advertisement
Answer
There is not real scrolling state in the browser; the scrolling event occurs, and then it’s done.
You could set a piece of state called e.g. isScrolling
to true
when the scrolling event occurs, and then set a timeout to set it back to false
after the last time it was scrolled.
Example
JavaScript
1
36
36
1
class App extends React.Component {
2
timeout = null;
3
state = {
4
isScrolling: false
5
};
6
7
componentDidMount() {
8
window.addEventListener("scroll", this.onScroll);
9
}
10
11
componentWillUnmount() {
12
window.removeEventListener("scroll", this.onScroll);
13
}
14
15
onScroll = () => {
16
this.setState({ isScrolling: true });
17
18
clearTimeout(this.timeout);
19
20
this.timeout = setTimeout(() => {
21
this.setState({ isScrolling: false });
22
}, 200);
23
};
24
25
render() {
26
return (
27
<div style={{ height: 5000, overflowY: "scroll" }}>
28
<div style={{ paddingTop: 50 }}>
29
{this.state.isScrolling ? "Hidden" : "Shown"}
30
</div>
31
</div>
32
);
33
}
34
}
35
36
ReactDOM.render(<App />, document.getElementById("root"));
JavaScript
1
4
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
3
4
<div id="root"></div>