George Mason University Antonin Scalia Law School

Sticky Nav on Scroll

Here’s a little JavaScript function to make your site’s header or navigation stick to the top of the window when users scroll the page:

HTML:

<div id="navigation">
  <!-- your navigation code -->
</div>

CSS:

#navigation{
  position:absolute;
  top:120px;
  left:0;
}
#navigation.fixed{
  position:fixed;
  top:16px;
}

JavaScript:

// Handles the page being scrolled by ensuring the navigation is always in view.
function handleScroll(){
  // check that this is a relatively modern browser
  if (window.XMLHttpRequest){
    // determine the distance scrolled down the page
    var offset = window.pageYOffset
               ? window.pageYOffset
               : document.documentElement.scrollTop;
    // set the appropriate class on the navigation
    document.getElementById('navigation').className =
        (offset > 104 ? 'fixed' : '');
  }
}
// add the scroll event listener
if (window.addEventListener){
  window.addEventListener('scroll', handleScroll, false);
}else{
  window.attachEvent('onscroll', handleScroll);
}

Source: “Detachable navigation using JavaScript