Performant Sticky Header Navigation In Pure JavaScript

Category: Javascript , Menu & Navigation , Recommended | July 2, 2017
Author:marcobiedermann
Views Total:1,989 views
Official Page:Go to website
Last Update:July 2, 2017
License:MIT

Preview:

Performant Sticky Header Navigation In Pure JavaScript

Description:

A high performance and pure JavaScript solution to make your header navigation sticky on scroll using CSS position: sticky property.

How to use it:

Create the header navigation following the html markup like this:

<header class="header sticky sticky--top js-header">
  <nav class="navigation">
    <ul class="navigation__list navigation__list--inline">
      <li class="navigation__item"><a href="#" class="is-active">Home</a></li>
      <li class="navigation__item"><a href="#">About</a></li>
      <li class="navigation__item"><a href="#">Contact</a></li>
      <li class="navigation__item"><a href="#">Blog</a></li>
      <li class="navigation__item"><a href="#">Social</a></li>
    </ul>
  </nav>
</header>

The primary CSS styles:

.header {
  background-color: #f7f7f7;
  padding-bottom: 1em;
  padding-top: 1em;
}

.header::after {
  bottom: 0;
  box-shadow: 0 0.0625em 0.5em rgba(0, 0, 0, .3);
  content: '';
  left: 0;
  opacity: 0;
  position: absolute;
  right: 0;
  top: 0;
  -webkit-transition: opacity 0.3s;
  transition: opacity 0.3s;
  z-index: -1;
}
.header.is-active::after {
  opacity: 1;
}
.navigation a {
  color: inherit;
  display: block;
  text-decoration: none;
}
.navigation .is-active {
  background-color: #000;
  color: #fff;
  padding-left: 1em;
  padding-right: 1em;
  border-radius: 999px;
}
.navigation__list {
  list-style: none;
  margin: -0.5em;
  padding: 0;
}
.navigation__list--inline {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}
.navigation__item {
  margin: 0.5em;
}

Stick the header navigation to the top using CSS position: sticky property:

.sticky {
  position: -webkit-sticky;
  position: sticky;
  will-change: transform;
}
.sticky--top {
  top: 0;
}

The primary JavaScript to add/remove classes depending on the scroll events.

function throttle(fn, delay) {
  var last = undefined;
  var timer = undefined;
  return function () {
    var now = +new Date();
    if (last && now < last + delay) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        fn();
      }, delay);
    } else {
      last = now;
      fn();
    }
  };
}
function onScroll() {
  if (window.pageYOffset) {
    $$header.classList.add('is-active');
  } else {
    $$header.classList.remove('is-active');
  }
}
var $$header = document.querySelector('.js-header');
window.addEventListener('scroll', throttle(onScroll, 25));

You Might Be Interested In:


Leave a Reply