testingtesting
testingtesting

Reputation: 163

How to trigger event in JS when reaching the bottom of the page in cases where there's no scroll

I have an event listener for scrolling to the bottom of the page that works fine:

document.addEventListener('scroll', () => {
    if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
        console.log("bottom reached");
    }
});

BUT my issue is that if the page loads and the document is shorter than the window, this won't trigger because there's no scroll event. The document fits in the window, in other words, so no need to scroll to the bottom.

I still want to trigger something in this case, though. How do I do that?

I thought about just having a conditional statement within a DOMContentLoaded event listener that checks if the window is bigger than the document, i.e.

if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
        console.log("window size exceeds page size");
}

While this works, it gives me a "forced reflow" performance violation warning in the console, basically saying this is taking too long.

Any advice on how to handle this?

Upvotes: 1

Views: 1774

Answers (1)

touchmarine
touchmarine

Reputation: 2058

Your solution is the simplest and if you do not have any other problems with it rather than the warning in the console, it might be the best.

Another way would be to use the Intersection Observer API, which is executed on load.

Here is a simple example:

<head>
<style>
.container {
    width: 100%;
    height: 80%;
    background-color: whitesmoke;
}
</style>
</head>
<body>
    <div class="container"></div>
    <script>
        const container = document.querySelector('.container')
        const observer = new IntersectionObserver(callback, {
            root: null,        // intersect with viewport
            rootMargin: '0px', // no margin when computing intersections
            threshold:  1.0,   // execute callback when every pixel is visible
        })
        function callback(entries) {
            for (const entry of entries) {
                if (entry.isIntersecting) {
                    console.log("i am also fired on load")
                }
            }
        }
        observer.observe(container)
    </script>
</body>

You could also observe your footer or some element at the bottom of the page. Using Intersection Observer you do not even have to use the scroll event listener.

Upvotes: 1

Related Questions