BruceyBandit
BruceyBandit

Reputation: 4334

Sticky nav bar re-appears when user scrolls

I am trying to create a bit of functionality where if the user scrolls down, the sitcky nav bar header will disappear. If the user scrolls up, it will re-appear.

I have almost got it, only issue is that when I scroll, the header disappears and only re-appears when I stop scrolling. Actually it sort of flickers before it re-appears.

This is what I am trying to achieve:

https://www.w3schools.com/howto/howto_js_navbar_hide_scroll.asp

HTML:

<header id="site-header" class="header-footer-group sticky-element-original element-is-sticky" role="banner" style="margin-top: 0px !important; margin-left: 0px !important; position: fixed; left: 0px; top: 0px; width: 651px; padding: 0px; z-index: 99999;">

...

</header>

Javascript:

<script>
/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("site-header").style.top = "0";
  } else {
      document.getElementById("site-header").style.top = "-100%";
  }
  prevScrollpos = currentScrollPos;
}
</script>

Upvotes: 4

Views: 602

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33943

The scroll event is a machine gun.... It fires like 10+ times on a single mousewheel spin.

Try buffering those event a bit... With a combination of clearTimeout/setTimeout:

/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */

let scrollTimeout

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("site-header").style.top = "0";
  } else {
      document.getElementById("site-header").style.top = "-100%";
  }

  // Event buffering here
  clearTimeout(scrollTimeout)
  scrollTimeout = setTimeout(function(){
    prevScrollpos = currentScrollPos;
  },500) // This delay may need adjustment...
}
#site-header{
  background: yellow;
}

#page{
  height: 50000px;
  background: blue;
}
<header id="site-header" class="header-footer-group sticky-element-original element-is-sticky" role="banner" style="margin-top: 0px !important; margin-left: 0px !important; position: fixed; left: 0px; top: 0px; width: 651px; padding: 0px; z-index: 99999;">

I'm the header... I know I'm ugly, but that is just a demo.

</header>

<div id="page"></div>

Upvotes: 1

Related Questions