How To Know Scroll End In Javascript

As a web developer, you might need to detect when a user has reached the end of a page or a scrollable container
in their browser. This can be useful for implementing features like infinite scrolling or loading more content
when the user reaches the bottom of a page. In this blog post, we’ll learn how to detect the scroll end using
JavaScript.

Detecting Scroll End

To detect the scroll end, we’ll use the window object and its properties related to scrolling.
Specifically, we’ll be using the following properties:

  • scrollY: The number of pixels that the document is currently scrolled vertically.
  • innerHeight: The height of the window’s content area (viewport) including scrollbars.
  • scrollHeight: The height of the entire document, including the portion that is not
    visible on the screen due to scrolling.

We can detect the scroll end by comparing the sum of scrollY and innerHeight
with the scrollHeight. If the sum is equal to or greater than the scrollHeight,
then the user has reached the end of the page.

Example: Detecting Scroll End

Let’s see an example on how to detect the scroll end using JavaScript.

window.addEventListener('scroll', () => {
    if (window.scrollY + window.innerHeight >= document.documentElement.scrollHeight) {
        console.log('You have reached the end of the page!');
    }
});

In this example, we add an event listener for the scroll event on the window
object. Inside the event listener, we check if the sum of scrollY and innerHeight
is equal to or greater than scrollHeight. If it is, we log a message to the console indicating
that the user has reached the end of the page.

Conclusion

In this blog post, we learned how to detect the scroll end using JavaScript by comparing the values of
scrollY, innerHeight, and scrollHeight. This technique can
be used to implement features like infinite scrolling or loading more content when a user reaches the bottom of
a page. Happy coding!