1

I am making the clone of a webpage which is made in JS but I am developing it by HTML, CSS, JS. Its navBar looks like this screenshot of navBar. Here is the link if you want to experience yourself link.

So, I have tried to implement this using IntersectionObserver API as well as by using window.addEventListener(). I don't want to implement this by using scroll event Listener because it is too heavy for end user.


const intersectionCB = ([entry]) => {
  const elem = entry.target;

  if (!entry.isIntersecting) {
    elem.classList.add('nav__2-sticky');
    // observer.unobserve(navBar);
  } else {
    elem.classList.remove('nav__2-sticky');
  }
};

const observer = new IntersectionObserver(intersectionCB, {
  root: null,
  threshold: 0
});
observer.observe(navBar);

In HTML file

        <div class="nav__2">
          <div class="row nav__2--content">
            <div class="logo-container">
              <img src="img/logo-black.png" alt="" class="logo" />
            </div>
........

In SCSS file

.nav {
  &__2 {
    top: 8rem;

    position: absolute;
    left: 0;
    width: 100%;
     
    &-sticky {
      position: fixed;
      top: 0;
    }
  }
}

You might understand what is happening. When navBar gets out of the view, (navBar is positioned at 8rem from top!). I append nav__2-sticky class (which is positioned fixed at 0 from top) to appear on the screen. Due to which entry.isIntersecting becomes true and elem.classList.remove('nav__2-sticky'); is executed. As a result navBar again gets out of the view and again elem.classList.add('nav__2-sticky') is executed. This cycle of adding and removing classes due to entry.isIntersecting becoming True and False is creating a problem for me. This happens in such speed that it shows abnormal behaviour.

So, is there any proper solution for this? I would also like to hear other solutions that might work.

peinearydevelopment
  • 11,042
  • 5
  • 48
  • 76

2 Answers2

1

I used scroll event after all. Here is the code, I think I don't need to explain. You will get more detailed explanation here link


const initialCords = navBar.getBoundingClientRect();
document.addEventListener('scroll', () => {
  if (window.scrollY > initialCords.top) {
    navBar.classList.add('nav__2-sticky');
  } else {
    navBar.classList.remove('nav__2-sticky');
  }
});

0

Another angle could be to run the intersection observer on an element that is out of view (below the bottom of the screen) and not only the navbar itself

Nine Magics
  • 637
  • 2
  • 8
  • 17