DEV Community

Discussion on: Detect if div is inside ViewPort

Collapse
 
tstark2 profile image
Todd Stark II

I'm not familiar with NextJS, but this seems like a good use case for the IntersectionObserver API. Intersection Observer essentially watches a specified area (the viewport, in your case) and basically emits an event when the item being watched for enters or leaves the viewport. That's a very simplified explanation, but it should at least give you an idea of what IntersectionObserver does and why I think it's a good solution to your problem, assuming you don't need to support IE.

It's possible that there's a NextJS specific way to do this as well, but if that's the case someone with more experience with that framework will need to chime in.

There are lots of tutorials out there on Intersection Observer, and even a few posts about it here on dev, so I'll leave exactly how to implement it up to you.

Here's a link to the MDN page for intersection observer, to get you started.

developer.mozilla.org/en-US/docs/W...