Home > Software design >  How to detect when a element is on/out of the view with Next and Typescript?
How to detect when a element is on/out of the view with Next and Typescript?

Time:11-11

I am building an app with Next and Typescript, the app has a nav bar on top of the screen, and need it to change style after a certain point of the view, I have been trying to use jQuery to achieve that result, but the whole window is undefined on dev mode and Typescript weird interactions with jQuery have been a problem. This is how the code looks like:

const Home: NextPage = () => {
  return (
    <>
      <nav id="myNav">
        <ul>
          <li>Item 1</li>
          <li>Item 2</li>
          <li>Item 3</li>
        </ul>
      </nav>
      <main>
        <div id="firstDiv">
         {//more code}
        </div>
        <div id="divToHideNav">
         {//more code}
        </div>
      </main>
    </>
  );
};

export default Home;

How can I change the nav style when it gets to the second div? I'm looking for any solution, with or without jQuery. Thanks in advance!

CodePudding user response:

If you want to change style after a certain point of the view, you can use Intersection Observer API and its polyfill (for internet explorer support). It will give you what you want. Take a look at here developer.mozilla.org/en-US/docs/Web/API/… –

what you are missing is, you are building an isomorphic app. so window and document will be undefined at server-side. you need to run your intersection observer callback inside of a useEffect or useLayoutEffect

this tutorial might help, i did not watch it but it seems like explains all youtube.com/watch?v=QD4GcZJObXg

  • Related