[Proposal] Element scroll listener


I have attempted to come up with an easier way to detect when an HTMLElement enters or exits the viewport. There have been many articles and libraries I’ve seen but none of them (at least to my knowledge) do not address entering, entered, exiting, exited events while providing offsets (to do something before the element actually shows in the viewport).

I’ve started a github project with a class called ElementListener that I would like to use as my proposal, but would love to get your thoughts on implementing something like this in the spec or whether or not you think it is worth it to pursue. To be honest, given that I use a class that should instantiated, I’m actually not even sure how best to implement something like this in the spec, so would love your thoughts on that also.

Thanks for your feedback and constructive criticism. :slight_smile:


This already exist: https://github.com/WICG/IntersectionObserver/blob/gh-pages/explainer.md


Oh nice. I actually didn’t know about that repo! I did take a look and it does seem more abstract than I expected for something like this. The amount of code you would have to write for such a rather small use case seems like overkill, but at least there is some traction on the idea. And I do like that they’ve found a way around using the scroll event which makes it much more performant. :slight_smile: Thanks for posting.


The code is actually quite small and easy to work with; the examples just look a little scary because they’re commented and solve real non-trivial problems. Those sorts of examples are great to learn from, but they always look a bit intimidating when you’re first trying to wrap your head around the concept.

The simplest way to use it, if you just want to listen to one element, is:

let el = ...;
let observer = new IntersectionObserver(changes=>{...});

Fill in the …s with your code.