How to avoid that IntersectionObserver cause a flickering behavior

142 Views Asked by At

I am adding a sticky nav in my website using IntersectionObserver, when the isIntersecting has passed from true to false, the website and nav starts flickering, in the background. The isIntersecting starts a loop between true and false causing this flickering behavior.

This is the JS code when I am applying the IntersectionObserver

const nav = document.querySelector(".nav-container");

const sticky = function (entries) {
  const [entry] = entries;
  console.log(entry);
  if (!entry.isIntersecting) {
    nav.classList.add("sticky");
  } else {
    nav.classList.remove("sticky");
  }
};

const navObserver = new IntersectionObserver(sticky, {
  root: null,
  threshold: 0,
});

navObserver.observe(nav);

This is the CSS

.nav-container {
  width: 100%;
  height: 10vh;
  position: relative;
  border-bottom: 1px solid rgba(0, 0, 0, 0.5);
}
.nav-container.sticky {
  position: fixed;
  z-index: 5;
}

This is the html

<header>
      <div class="discount-banner">
        <p>10% OFF ON ALL ORDERS USE THE CUPON ModaWave77</p>
      </div>
      <div class="title-container">
        <h1>ModaWave</h1>
      </div>
      <nav class="nav-container">
        <ul class="nav-items-container">
          <li id="women">WOMEN´S CLOTHING</li>
          <li id="men">MEN´S CLOTHING</li>
          <li id="jewelry">JEWELRY</li>
        </ul>
        <div class="cart_preview-container hidden">
          <div class="cart-item">
            <button>Proceed Payment</button>
          </div>
        </div>
        <i
          class="fa fa-shopping-cart fa-4x"
          id="cart-icon"
          aria-hidden="true"
        ></i>
      </nav>
    </header>

My expectation is to keep the nav fixed to the top once this one is set to isIntersecting=false, meaning that when I scroll down I want to keep visible the nav, I did it successfully in another project but not in this one.

This is an screenshot of the website and the nav

This is my console when I scroll down, it keep switching between isIntersecting: true and false

0

There are 0 best solutions below