In large applications we might have observed that extra data is loaded when the user reaches the bottom of the page. This is very crucial because there can be a large set of data which need not be fetched initially as the user may not see all of those. In that case we can use infinite scrolling technique where the data is fetched only when the user reaches the end of the screen.
So , here comes the question how to check whether the user has reached the end or not. DOM makes our things easy.
Now , we will see three properties called ClientHeight , ScrollTop , ScrollHeight.
- ClientHeight — It is the inner height of a html element including padding and excluding borders , margins and horizontal scrolling.
It is a read-only property which is in pixels.
2. ScrollTop -It is the amount of pixels an element is scrolled down from its position vertically. If there is no vertical scroll bar ScrollTop of the element will be zero.
3. ScrollHeight — It is the total height of the element’s content including the content which is not seen due to overflow .(A scrollbar comes in the situation).
Now if we observe this carefully we can create a relation between these three attributes i.e clientHeight + scrollTop ≥ scrollHeight.
We do this on the root element of the DOM. We can get the root element of the DOM using document.documentElement.
Sum of total clientHeight i.e the element’s innerHeight and the amount of pixels the element scrolled vertically should be greater than the element’s content total height.
We can add a eventListener like this
Here , in fetchPatients function we can do a api call to fetch data , we can add spinner to show user the data is being fetched.