koder613
koder613

Reputation: 1576

Sticky navbar glitchy/shaky when resized on scroll bootstrap

I am trying to shrink the navbar and change the color when the user scrolls down, I am trying to make this not happen instantly so I added a transition css property to make this change gradual.

However, after testing my code out, there appears to be a serious glitch. At a certain point, the navbar shakes violently up and down and glitches.

Could anyone help me with this?

I saw a very similair question here: Bootstrap fixed navbar is glitchy and shaky on scrolling. But I couldn't see an answer to the issue.

My code below. (JSFiddle: https://jsfiddle.net/koder613/vqxrg8p7/9/)

HTML:

<nav class="navbar navbar-expand-md navbar-light bg-light sticky-top">
    <a class="navbar-brand" href="/"><img src="https://live.staticflickr.com/5576/14671748429_f5887e51b0_b.jpg" width="200"  class="d-inline-block align-top" alt="Logo" loading="lazy"/></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
      </ul>
    </div>
  </nav>
  
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>
  <p>
  Text to enable scroll
  </p>

CSS:

.navbar{
    padding: .6rem 1.3rem ;
    transition: all 0.5s;
}
.navbar-brand img{
    transition: all 0.5s;
}
.c4d4e4{
    background-color: #c4d4e4!important;
}

JavaScipt(jQuery):

$(window).on('scroll', () => {
    if ($(window).scrollTop() > 80){
          $('.navbar').addClass('c4d4e4')
          $('.navbar-brand img').css('width', '20%')
    } else {
          $('.navbar').removeClass('c4d4e4')
          $('.navbar-brand img').css('width', '')
    }
});

Upvotes: 2

Views: 1531

Answers (1)

koder613
koder613

Reputation: 1576

I fixed the issue by changing the the class in the navbar sticky-top to fixed-top. This changes position: sticky; to position:fixed;.

This fixed the issue because a sticky position somehow changes the scrollTop calculation.

Upvotes: 3

Related Questions