Sviat Kuzhelev
Sviat Kuzhelev

Reputation: 1788

On Mobile why pageYOffset + clientHeight don't equal to scrollHeight?

For some reason on mobile devices (iPhone X for concretely) I got some magic with coords, where the full page height based on page's offset + current heights sum don't equal to the main document value:

const fullHeight = window.pageYOffset + document.documentElement.clientHeight

fullHeight !== document.documentElement.scrollHeight // why?

For example:

console.log(document.documentElement.clientHeight) // 635 console.log(window.pageYOffset) // 905 console.log(document.documentElement.scrollHeight) // 1675 !== (635 + 905)

Sum: 635 + 905 => 1540 !== 1675

I found that something hidden adds extra height to the clientHeight value. This happens only on mobile (tested on iPhone X os13, Chrome + Safari), btw on the desktop all works fine as expected, why...

Update:

I've made some fast solution to deal with this magic and be notified once we hit the bottom of the page:

    const fullPageHeight = document.documentElement.scrollHeight
    const scrollTop = window.pageYOffset
    const currentScreenHeight = fullPageHeight - scrollTop

    const isBottomNotHit = currentScreenHeight + scrollTop !== fullPageHeight

It works well on both mobile and desktop devices though.

Upvotes: 2

Views: 1962

Answers (1)

Sviat Kuzhelev
Sviat Kuzhelev

Reputation: 1788

Finnaly, I've made a good solution for anyone who hit this problem too:

const lazyLoadScrollChecker = () => {
  const _configuration = {
    windowHeight: window.innerHeight,
    fullPageHeight: document.documentElement.scrollHeight,
    scrollTop: window.pageYOffset
  }

  const _calcCurrentScrollPosition = () => _configuration.fullPageHeight - _configuration.scrollTop

  const _checkScreenCoords = () => {
    const { windowHeight, fullPageHeight, scrollTop } = _configuration

    return {
      isBottomHitOnScroll: _calcCurrentScrollPosition() + scrollTop === fullPageHeight,
      isBottomHitOnInitView: windowHeight === fullPageHeight
    }
  }

  return _checkScreenCoords()
}

export default lazyLoadScrollChecker

It help me a lot. Cheers!

Upvotes: 2

Related Questions