Skip to content Skip to sidebar Skip to footer

Change Static Navbar To Fixed On Scroll When Bottom Of Hero Section Is Reached

How can I make the static positioned navigation bar become fixed when the end of specific section is reached? Fiddle $(document).on('scroll', function() { var navbar = $('.stat

Solution 1:

EDIT I added the slideDown feature, as asked in comments... And it is looking great!

Two things to say about this add:

  1. .slideDown() is intended to animate a hidden element. So in your case, you have to hide it first.
  2. Then, a "flag" is needed to avoid it being animated too many times...The scroll event is firing like an AK47! ;)
  3. About the slideUp(), you have to wait the end of the animation to remove the class making it fixed, then ensure it isn't hidden. So you do this in the slideUp() callback.


I guess you want something like in this snippet.

You just have to compare how many pixels were scrolled, using .scrollTop() to the .fullscreenheight value.

Then it is easy to set your navigation bar as fixed or static.

// Navigation state "flag"var isFixed=false;

$(document).on("scroll", function() {
  var navbar = $(".static-navbar");
  var heroSectionHeight=$(".fullscreen").height();

  // Set fixedif( $(window).scrollTop()>=heroSectionHeight && !isFixed ){
    isFixed=true;
    navbar.hide().addClass("fixed-navbar").slideDown(600);
  }

  // Set staticif( $(window).scrollTop()<heroSectionHeight && isFixed ){
    isFixed=false;
    navbar.slideUp(600,function(){
      navbar.removeClass("fixed-navbar").show();
    });
  }
});
body {
  margin: 0;
}
.fullscreen {
  width: 100%;
  height: 100vh;
  background-color: #000;
  color: #fff;
  text-align: center;
}
.bg-red {
  background-color: red;
}
.static-navbar {
  width: 100%;
  position: static;
  padding: 25px0;
  background-color: rgba(0, 0, 0, 1);
  border-bottom: 1px solid rgba(255, 255, 255, .15);
}
.fixed-navbar {
  position: fixed;
  background-color: rgba(255, 255, 255, 1);
  color: #000;
  border-bottom: 1px solid rgba(255, 255, 255, .15);
}
<scriptsrc="https://code.jquery.com/jquery-3.2.1.min.js"></script><divclass="fullscreen"><navclass="static-navbar">
    Static Navbar
  </nav><divstyle="padding-top: 280px;">HERO SECTION</div></div><divclass="fullscreen bg-red"style="padding-top: 50px; padding-bottom: 50px;"><divstyle="padding-top: 280px;">RED SECTION</div></div>

This snippet is better seen in full page mode(Otherwise, the height is too small and it flickers)

Post a Comment for "Change Static Navbar To Fixed On Scroll When Bottom Of Hero Section Is Reached"