简体   繁体   中英

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 = $(".static-navbar");
    navbar.addClass("fixed-navbar");
})

Im trying to make the navigation bar become fixed as soon as "red section" is reached.
With this jQuery code above, I managed to get it fixed as soon as the scroll event is fired, but that's not what I'm looking for.

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 .fullscreen height 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 fixed if( $(window).scrollTop()>=heroSectionHeight && !isFixed ){ isFixed=true; navbar.hide().addClass("fixed-navbar").slideDown(600); } // Set static if( $(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: 25px 0; 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); } 
 <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <div class="fullscreen"> <nav class="static-navbar"> Static Navbar </nav> <div style="padding-top: 280px;">HERO SECTION</div> </div> <div class="fullscreen bg-red" style="padding-top: 50px; padding-bottom: 50px;"> <div style="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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM