Your algorithm seems to be a bit off at the moment.
Now, if you scroll just a little below $ (". Carousel"). externalHeight ()
-> fixed does not work true, so navbar never loses the navbar-fixed-top class.
You have to change this
if ($(window).scrollTop() < $(".carousel").height() + ghostElHeight) {
to
if ($(window).scrollTop() < $(".carousel").height()) {
then it works as expected. ghostElHeight course you don't have to bother with ghostElHeight . Just add navspacer to the HTML and switch it with show / hide.
And for another problem: you enter the lastfixed variable, which makes the code complicated. best way without lastfixed :
change your algorithm from
fixed = true; if (fixed === lastfixed) return
to
if (fixed == true) return fixed = true;
and the same for the false part. it is simpler and more understandable.
Full JS code:
$(function () { var fixed = false; $(document).on( 'scroll', function(){ if($(window).scrollTop()>=$(".carousel").outerHeight()) { if (fixed == true) return fixed = true; $(".navbar").addClass("navbar-fixed-top"); $(".navspacer").show(); } if($(window).scrollTop()<$(".carousel").height()) { if (fixed == false) return fixed = false; $(".navbar").removeClass("navbar-fixed-top"); $(".navspacer").hide(); } }); });
and add navspacer manually after navigation:
<div style="height:100px; display: none;" class="navspacer"> </div>
Demo
source share