probablybest probablybest - 1 month ago 7
CSS Question

Stop sticky sub navigation from jumping into place

I have a main fixed navigation but I also have a sub nav that is picked up later on in the page.

When you scroll past the

#secondary-nav
div it adds a class of
.sticky
adding
position:fixed
to the div. However it does this after you have already scrolled passed it then jumps into place under the main navigation. How can I smooth this out so it looks like its being smoothly added as you scroll past it and then placed back again if you scroll up?

Here is my fiddle.

HTML:

<nav id="top-wrapper">I'm a sitcky navigation</nav>
<div id="hero">
hero image!
</div>
<nav id="secondary-nav">
I'm the secondary nav.
</nav>
<div id="content">
I'm the content, scroll down!
</div>


jQuery:

$(window).scroll(function () {
if ($(document).scrollTop() === 0) {
$('#top-wrapper').removeClass('sticky ');
} else {
$('#top-wrapper').addClass('sticky ');
}
});

$(document).ready(function () {
$(function () {
var nav = $('#secondary-nav');
if (nav.length) {
var stickyNavTop = nav.offset().top;
$(window).scroll(function () {
if ($(window).scrollTop() > stickyNavTop) {
$('#secondary-nav').addClass('sticky');
} else {
$('#secondary-nav').removeClass('sticky');
}
});
}
});
});

Answer

I try adding - 100 in your top offset in your jquery code. Check this fiddle. https://jsfiddle.net/fgfb9cpq/1/. and update the top in secondary nav.

$(document).ready(function () {
    $(function () {
      var nav = $('#secondary-nav');
      if (nav.length) {
          var stickyNavTop = nav.offset().top - 100;
          $(window).scroll(function () {
              if ($(window).scrollTop() > stickyNavTop) {
                  $('#secondary-nav').addClass('sticky');
              } else {
                  $('#secondary-nav').removeClass('sticky');
              }
          });
      }
    });
});