Sticky Navigation Bar on Page Scroll with jQuery

In this article we learn how to setup sticky navigation bar when you scroll page to navigation bar. And when user scroll back to top navigation  bar will back to it’s position.

So here are some simple steps you need to follow.

1. Create HTML for navigation bar.

<div class="header">
  <h1>Scroll Down</h1>
  <p>Scroll down to see the sticky menu effect.</p>
</div>
<nav id="navbar">
  <a class="active" href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Blog</a>
  <a href="#">Contact</a>
</nav>
<div class="content">
  <h2>Sticky Navigation Example</h2>
  <p>In this example it make navigation bar sticky when you scroll to navigation bar and it make sticky to navigation bar on top.</p>
</div>

In this we set navigation bar HTML.

2. Write css for navigation bar.

body{
  margin:0;
}
.header{
  text-align:center;
  padding:20px 10px;
}
nav{
  background:#000;
  padding:10px 0;
  font-size:16px;
  text-align:center;
}
nav a{
  color:#fff;
  text-decoration:none;
  padding:10px;
  font-size:16px;
  font-weight:600;
}
nav.sticky{position:fixed; width:100%;top:0;}
.content{
  height:600px;
  padding:20px;
}

In this CSS if you check we did not set position fixed to nav tag CSS. For this we added another css class as .sticky and in this we apply position:fixed property. So when user scroll down to page to navigation section jQuery will add this .sticky class to nav bar tag.

3. Add jQuery for sticky navigation bar.

For this remember you have to include jQuery library first in your HTML. then add below jquery code.

$(document).ready(function(){
    var navtop = $('#navbar').offset().top;
    $(window).scroll(function() {
        if ($(this).scrollTop() >= navtop){ 
             $('nav').addClass("sticky");
        } else {
             $('nav').removeClass("sticky");
        }
    });
});

In this jQuery we will write our code on window scroll event. First we get top offset for our navigation bar.  Then we compare scroll bar top offset with navigation bar top offset. If scroll bar top offset is greater then equal to navigation bar top offset then we add sticky class in our navigation bar container. and if scroll bar top offset is less then navigation bar top then it will remove sticky class from navigation container.

You can check this working example on codepen.

See the Pen Sticky Menu on Scroll by Webcodecraft (@Webcodecraft) on CodePen.