Checking if an element has scrolled into view.
I’ll keep this short and sweet because it took me a while to get this just right.
Here’s the snippet
let hasScrolledIntoView = (element) => {
const rect = element.getBoundingClientRect();
return (rect.top < window.innerHeight && rect.bottom >= 0;
}
What’s going on here?
We have a function that takes in an html element.
We get the bounding rectangle.
We return if the top position of the element is < the window’s inner height and the bottom position of the element is ≥ 0.
What do I do with this?
Slap this function inside one of these on scroll babies:
addEventListener("scroll", (event) => {
hasScrolledIntoView(el);
});
Make sure your el
variable is a thing.
And you’re good to go!
See ya next time!
Why do I want to use this?
I didn’t want to find a library to tell me this info and I didn’t want to do offset math.
I originally posted this on medium, you can follow me there:
https://medium.com/p/8f92dcbd6b05
Top comments (2)
I'd have a look at Intersection observers they're quite a bit lighter (by only firing when somethings enters or leaves a zone).
Oh wow!
That's awesome!