[removed] How to detect if browser window is scrolled to bottom?

后端 未结 19 982
你的背包
你的背包 2020-11-22 16:00

I need to detect if a user is scrolled to the bottom of a page. If they are at the bottom of the page, when I add new content to the bottom, I will automatically scroll them

相关标签:
19条回答
  • 2020-11-22 16:30

    You can check if the combined result of the window's height and scroll top is bigger than that of the body

    if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {}

    0 讨论(0)
  • 2020-11-22 16:31

    Using defaultView and documentElement with functional code snippet embedded:

    const { defaultView } = document;
    const { documentElement } = document;
    const handler = evt => requestAnimationFrame(() => {
      const hitBottom = (() => (defaultView.innerHeight + defaultView.pageYOffset) >= documentElement.offsetHeight)();
      hitBottom
        ? console.log('yep')
        : console.log('nope')
    });
    document.addEventListener('scroll', handler);
    <pre style="height:110vh;background-color:fuchsia">scroll down</pre>

    0 讨论(0)
  • 2020-11-22 16:31

    The accepted answer did not work for me. This did:

    const element = document.createElement('div');
    document.body.appendChild(element);
    document.addEventListener('scroll', () => {
        const viewportHeight = window.innerHeight;
        const distance = element.getBoundingClientRect().top;
        if (Math.floor(distance) <= viewportHeight) {
            console.log('yep')
        } else {
            console.log('nope')
        }
    })
    
    0 讨论(0)
  • 2020-11-22 16:32
    window.onscroll = function(ev) {
        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
            // you're at the bottom of the page
        }
    };
    

    See demo

    0 讨论(0)
  • 2020-11-22 16:32

    You can look into jquery's infinite scroll:

    http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/

    Which sounds like it does what you're asking for, assuming you're willing to use the jquery library and not hoping for a strict pure JS method.

    0 讨论(0)
  • 2020-11-22 16:32
    const handleScroll = () => {
        if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
            onScroll();
        }
    };
    

    This code worked for me in Firefox and IE as well.

    0 讨论(0)
提交回复
热议问题