Search code examples
javascriptcssscrollnavbaroffset

How to modify this navbar to hide on scroll down only after 100px?


I currently have a navbar that on scroll down disappears and on scroll up reappears again (and is always visible when at the top of the page).

This works fine on desktop - the nav always shows when the page is at the top, but on mobile devices glitches and disappears completely when at the top of the page.

How would I amend this to be visible on scroll down for the first 100px, then disappear until user scrolls up?

var prevScrollpos = window.pageYOffset;
window.onscroll = function () {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById('mainNav').style.top = '0';
  } else {
    document.getElementById('mainNav').style.top = '-100px';
  }
  prevScrollpos = currentScrollPos;
};

Solution

  • Solution

    var prevScrollpos = window.pageYOffset;
    window.onscroll = function () {
      var currentScrollPos = window.pageYOffset;
      if (prevScrollpos > currentScrollPos || currentScrollPos <= 100) {
         document.getElementById('mainNav').style.top = '0';
      } else {
         document.getElementById('mainNav').style.top = '-100px';
       }
      prevScrollpos = currentScrollPos;
    };