nav-scroll.js

This script toggles the visibility of a target element when the user scrolls the page. It hides the element on downward scroll and reveals it on upward scroll, helping maximize content visibility while maintaining easy access to navigation or headers.

Purpose 🚀

  • Hide/Show UI Elements: Automatically conceal a header or navigation bar when scrolling down.
  • Improve UX: Provide more screen space for content on long pages.
  • Lightweight: No external dependencies; works with vanilla JavaScript.

How It Works 🔄

  1. Initialization
    • Capture the initial vertical scroll position in prevScrollpos.
  2. Scroll Event Listener
    • On every window.onscroll, read the new scroll offset.
  3. Direction Detection
    • Compare the new offset with prevScrollpos.
  4. Toggle Class
    • If scrolling down, add the .topHide class to the target element.
    • If scrolling up, remove the .topHide class.
  5. Update State
    • Assign the new offset to prevScrollpos for the next comparison.
flowchart TD
    A[User scrolls] --> B{New offset > Prev offset?}
    B -->|Yes (down)| C[Add `.topHide`]
    B -->|No (up)| D[Remove `.topHide`]
    C --> E[Set Prev = Current]
    D --> E

Key Variables ⚙️

Variable Description
prevScrollpos Last recorded vertical scroll offset (px).
currentScrollPos Current vertical scroll offset (px).
element The DOM node with id="hideOnScroll".

Code Implementation 📝

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
  var currentScrollPos = window.pageYOffset,
      element = document.getElementById("hideOnScroll");
  if (prevScrollpos < currentScrollPos) {
    element.classList.add("topHide");
  } else {
    element.classList.remove("topHide");
  }
  prevScrollpos = currentScrollPos;
};

Source: nav-scroll.js

HTML Integration 📄

  • Include the script just before </body>:
    <script src="js/nav-scroll.js"></script>
    
  • Mark the element you wish to hide/show:
    <header id="hideOnScroll">
      <!-- Navigation content -->
    </header>
    

Styling the Hidden State 🎨

Ensure your CSS defines the .topHide class to slide or fade out the element. For example:

#hideOnScroll {
  transition: transform 0.3s ease;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
}

.topHide {
  transform: translateY(-100%);
}

Browser Support 🌐

  • Utilizes window.pageYOffset and Element.classList.
  • Supported in all modern browsers.
  • For IE9 and below, consider a polyfill for classList.

Potential Improvements 💡

  • Debounce/Throttle the scroll handler to boost performance on heavy pages.
  • Configurable Selector: Allow passing a custom target ID or class.
  • Passive Listeners: Use { passive: true } to optimize scrolling on touch devices.