3

Using the IntersectionObserver you can detect if an element has scrolled into viewport, but is is possible to detect if the viewport itself has scrolled a certain number of px from the top?

What I'm trying to do: I have an infinite scroll set up using IntersectionObserver which works fine. But I want to show a fixed positioned Scroll back to top button in the lower bottom/right corner of viewport — but I only want to show that if the user scrolls, say 200-300px from the top.

GN.
  • 8,672
  • 10
  • 61
  • 126
  • Intersection Observer is usually used by children. You're perhaps interested in the state of the documentElement.scrollTop. Correct me if I'm wrong. A page scroll (N-px) position has everything to do with showing a fixed "ScrollToTop" button on the bottom right corner. IntersectionObserver - not much. A fixed button intersects with nothing. – Roko C. Buljan Jul 24 '20 at 21:59
  • yes and no. I'm not showing the fixed button based on what IT intersects with. I'm showing it based on the scrollTop of the document. I've managed to implement infinite scroll without doing a bunch of `documentElement.scrollTop` measurements — so my question is whether it is possible to use `IntersectionObserver` to detect document scroll position.. – GN. Jul 24 '20 at 22:06

1 Answers1

0

Somewhat late to the party but you can use intersection observer quite easily for this. You observe an element above the fold as it goes out of view change the 'scroll back to top' state. Easy as pie. This is way more efficient that messing with scroll events as it can block the main thread. MDN docs go into more depth.

OStraight
  • 11
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 04 '22 at 14:43