Sticky Pos

by bhupendra negi

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/stickyfill/2.1.0/stickyfill.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=IntersectionObserver"></script>
<div id="logo-container"></div>
<div id="nav-container-top"></div>
<div id="nav-container">This element will get sticky scroll </div>
<div id="main-container"></div>

CSS

body {
  margin: 0px;
  font-family: Roboto, Tahoma;
}

#logo-container {
  background-color: #bdc3c7;
  height: 100px;
}

#nav-container-top {
  background-color: #bdc3c7;
  min-height: 1px;
  min-width: 1px;
}

#nav-container {
  background-color: #2980b9;
  height: 60px;
  line-height: 60px;
  color: white;
  text-align: center;
  font-size: 25px;
  position: -webkit-sticky;
  /* for safari */
  position: sticky;
  top: 0px;
  font-weight: 700;
  transition: font-size 0.2s ease-in;
}

#nav-container:after {
  content: ' down 👇' 
}

.nav-container-sticky {
  background-color: #e74c3c !important;
  font-size: 18px !important;
}

#nav-container.nav-container-sticky:after {
  content: 'up ☝'
}

#main-container {
  background-color: #ecf0f1;
  height: 2000px;
}

JavaScript

//Ie fallback
var element = document.querySelector('#nav-container');
Stickyfill.add(element);


var observer = new IntersectionObserver(function(entries) {
  // no intersection with screen
  if (entries[0].intersectionRatio === 0)
    document.querySelector("#nav-container").classList.add("nav-container-sticky");
  // fully intersects with screen
  else if (entries[0].intersectionRatio === 1)
    document.querySelector("#nav-container").classList.remove("nav-container-sticky");
}, {
  threshold: [0, 1]
});

observer.observe(document.querySelector("#nav-container-top"));