DEV Community 👩‍💻👨‍💻

Niko Montana
Niko Montana

Posted on

Detect if div is inside ViewPort

I am using NextJS and want to show a Button when the User scrolls to a particular Element. Unfortunately I cannot get it really working.

I have a Layout File, which gets shared across all Components.

import Navbar from "./Navbar";
import Footer from "./Footer";

const Layout = props => {
  return (
    <div>
      <Navbar />
      {props.children}
      <Footer />
    </div>
  );
};

export default Layout;

I tried to implement onScroll to the first <div/>in the Layout file but it does not get triggered.

Top comments (1)

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...

Tired of sifting through your feed?

You can change your feed and see more relevant posts by adding a rating to different tags on DEV. Head here to adjust your weights.