Cory’s Coding Tips

Cory Harkins
1 min readOct 13, 2023

--

Checking if an element has scrolled into view.

Cory’s Coding Tips

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.

--

--

Cory Harkins
Cory Harkins

Written by Cory Harkins

Here to learn and grow as a programmer.

No responses yet