Make Bootstrap Navbar sticky

The simple way to make bootstrap navbar sticky , just add class name sticky-top to your navbar. But its only working if navbar element had direct child of body. If the navbar wrap in some other div it will not work.

So if  so many div is used in navbar child, we need to use some JavaScript to make it sticky , 


document.addEventListener("DOMContentLoaded", function(){
  window.addEventListener('scroll', function() {
      if (window.scrollY > 50) {
        document.getElementById('navbar_Id').classList.add('fixed-top');
        // add padding top to show content behind navbar
        navbar_height = document.querySelector('.navbar').offsetHeight;
        document.body.style.paddingTop = navbar_height + 'px';
      } else {
        document.getElementById('navbar_top').classList.remove('fixed-top');
         // remove padding top from body
        document.body.style.paddingTop = '0';
      } 
  });
}); 




Need to change : 

 
change the code navbar_id with your own navbar 


subject to change : 




Understanding of code : 


  • Now check if window scrolled window.addEventListener('scroll', function() { ... }
  • Check if scrolled more than x amount of px if (window.scrollY > 50) { ... }
  • Select navbar element and add function classList.add('fixed-top'); to fix on top
  • Remove class fixed-top when page scrolled back to top