There occurs situation sometime where we need to detect if we have scrolled down to the bottom of the window or not.
For example suppose you are creating a lazy loading feature in which you need to check if you have reached to the scroll limit in order fetch the additional data.
Detect if window is scrolled to the bottom.
There are three different things that window and document property of browser provide us which we will be using in order to detect the scroll end.
const scrollEnd = (window.innerHeight + window.scrollY) >= document.body.offsetHeight;
innerHeight
gives the available height of the window in which data is placed and scrollY
gives the scroll position.
We combine them together to check if we have reached to end of the body by comparing it with document.body.offsetHeight
.
This works fine but the scrollY
property is not available in the IE browsers.
So here is the work around which we can use.
const scrollEnd = (window.innerHeight + window.pageYOffset) >= document.body.offsetHeight;
pageYOffset
gives us the pixels of the current document has scrolled from the upper left corner of the window horizontally.
Scrolled position in MAC.
This works perfectly in all the browsers except in MAC. In mac we need to reduce few pixels from the calculation.
const scrollEnd = (window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2;
If you want to check for a particular element then us the following.
const d = document.documentElement; const offset = d.scrollTop + window.innerHeight; const height = d.offsetHeight; const scrollEnd = offset >= height;