It is also useful to detect when a user scrolled to the bottom of a page and you can perform some action whenever it happens. For example, you can load more data when users reach to the bottom. It adds the infinite scrolling feature to your webpage.
document.documentElement element, which represents the root element of the document (i.e., the
This element has the
scrollHeight property that represents the total height of the entire page, from the very top to the very bottom, including any parts that are currently hidden from view and require scrolling to access.
You also need to use the
window.innerHeight property. It represents the height of the viewport, which is the area of the web page that is visible inside the browser window without any scrolling.
These two properties are used to calculate the total scrollable height of a page:
document.documentElement.scrollHeight– Returns the total height of an entire page.
window.innerHeight– Returns the height of a web page area that is visible without any scrolling.
const scrollbarHeight = document.documentElement.scrollHeight - window.innerHeight console.log(scrollbarHeight)
window.innerHeight from the
document.documentElement.scrollHeight value to find the scrollable height of a page. This is the difference between the total height of the web page and the height of the visible viewport.
This value represents the amount of space you need to scroll in order to reach the bottom of your webpage.
scrollHeight– Returns the total height of the element's content, including any content that overflows and is not visible.
clientHeight– Returns the visible height of an element inside its content box, without including any space that may be added by its border or margin.
const element = document.getElementById('my-element'); // replace 'my-element' with the ID of your element const scrollableHeight = element.scrollHeight - element.clientHeight; console.log('Scrollable height: ', scrollableHeight);
clientHeight property value from the
Also Read: Ultimate Guide to Create Custom Scrollbars in CSS
Like, whenever a user goes to the bottom of your page, you can show a "Back to top" button. If a user clicks this button, it will scroll the user back to the top of the page automatically.