IntersectionObserver detect scrolled n px from top?

Viewed 924

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.

1 Answers

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.

Related