Reputation: 4306
Hello I am trying to check if an user scrolled the bottom of the page.
I am using this function to check:
const handleScroll = (event) => {
const bottom = event.target.scrollHeight - event.target.scrollTop === event.target.clientHeight;
if(bottom){
console.log('hello');
}
}
But the thing is my app looks like this :
Right now the function only works when the inner scrollbar is at the bottom. However i want it to fire when the outer scrollbar reached the bottom.
The entire code looks like this :
const handleScroll = (event) => {
const bottom = event.target.scrollHeight - event.target.scrollTop === event.target.clientHeight;
if(bottom){
console.log('hello');
}
}
return (
<div className='main' onScroll = {handleScroll}>
<div className='project-counter'>{filteredProjects.length > 0 ? (<p>Gevonden projecten : {filteredProjects.length}</p>) : null}</div>
{pro.map(project => (
<div className='view-container' key={project._id}>
<div className='hours-container'>
<table>
<tr>
<th className='tb-first'>Datum</th>
<th className='tb-first'>medewerker</th>
<th>Dienst</th>
<th>Toelichting</th>
<th>Aantal</th>
</tr>
{project.projectHours.map(hour => (
<tr>
<td>{hour.created_at}</td>
<td>{hour.employee.name}</td>
<td>{hour.type.label}</td>
<td>{hour.note}</td>
<td>{hour.hours.toFixed(2)}</td>
</tr>
))}
</table>
</div>
</div>
))}
</div>
)
Upvotes: 4
Views: 10869
Reputation: 11610
Add the listener to the window object:
const App = () => {
const handleScroll = () => {
const bottom = Math.ceil(window.innerHeight + window.scrollY) >= document.documentElement.scrollHeight
if (bottom) {
console.log('at the bottom');
}
};
React.useEffect(() => {
window.addEventListener('scroll', handleScroll, {
passive: true
});
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
return <div className = "👀" > 👀 < /div>
};
ReactDOM.render( < App / > , document.getElementById("root"));
.👀 {
height: 200vh;
width: 100%;
background-color: mediumseagreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.development.js"></script>
<div id="root"></div>
Upvotes: 16
Reputation: 793
For me it looks like your inner scrollbar belongs to your div
. Do you have a Component one level higher? Try to find the outer scrollbar in the browser's developing mode (F12) and see to which Element it belongs. If it's another div element, then just add the listener with the function handleScroll
to that Element.
Upvotes: 0