简体   繁体   中英

Bootstrap Navbar Fadeout after Scrolling Certain Distance

Everything I've found so far on the net concerns fading on waypoint or x distance scrolled.

However, I need my navbar to fade out after moving a certain distance regardless of where the scroll begins on the page.

So far, I've gotten it to fade in and out on scroll action alone. I've played with a few different methods stumbled upon here and on codepen where I've posted the code. This seems the best method so far although it feels glitchy on mobile. I've read somewhere this kind of code however shouldn't be used for mobile platforms.

To be more objective here, I'd like the navbar to fadeOut when scrolling down a distance of 1/3 the screen REGARDLESS of starting point.

Below is the JS code thanks to member Tushar.

Full working code can be found here on codepen .

var lastScrollTop = 0, delta = 5;
    $(window).scroll(function(event){
       var st = $(this).scrollTop();

       if(Math.abs(lastScrollTop - st) <= delta)
          return;

       if (st > lastScrollTop){
           // downscroll code
           $(".navbar").fadeOut()
       } else {
          // upscroll code
          $(".navbar").fadeIn();

       }
       lastScrollTop = st;
    });

This is more of an update and the best "working" solution I was able to come up with so far.

  • Using .stop() seems to remove some of the glitches on mobile platforms.
  • I've added another if statement that forces the navbar to appear when x amount away from the top. And when beyond that the old code takes over.

The problem so far is that I notice the fade only triggers when the scroll comes to a complete stop. This ruins user experience. The above patches with increasing fade speed seem to make for a smoother experience on mobile.

var lastScrollTop = 0, delta = 5;
/*window.addEventListener("scroll", function()*/

$(window).scroll(function(event){
  var st = $(this).scrollTop();

  if(Math.abs(lastScrollTop - st) <= delta)
    return;

  if (st > lastScrollTop){
    // downscroll code
    $(".navbar").stop().fadeOut('fast')
  } else {
    // upscroll code
    $(".navbar").stop().fadeIn('fast');

  }if (window.scrollY < 500) {
        $('.navbar').stop().fadeIn('fast');
    }
  lastScrollTop = st;
});

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