DEV Community

Cory Harkins
Cory Harkins

Posted on

Cory’s Coding Tips

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (2)

Collapse
 
link2twenty profile image
Andrew Bone

I'd have a look at Intersection observers they're quite a bit lighter (by only firing when somethings enters or leaves a zone).

Collapse
 
charkinsdevelopment profile image
Cory Harkins

Oh wow!
That's awesome!

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay