Others



Create Sticky Navar Using CSS and JavaScript


Sticky navbar is a fixed navigation bar in given offset position.It will stick to the top when user scroll down the page.The following example shows how to create sticky navbar using JavaScript and CSS.

Example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  /*Navbar Style Properties*/
  html,body{
    margin:0;
    padding:0;
  }
  nav{
    width:100%;
    background-color:#ccc;
    padding:5px 20px;
  }
  nav ul{
    list-style-type:none;
  }
  nav ul li{
    display:inline;
    margin-right:20px;
  }
  nav ul li a{
    text-decoration:none;
    color:white;
    font-weight:1rem;
  }
  .header-text{
    padding:10px 20px;
    text-align:center;
  }
  .container{
    padding:10px 20px;
    min-height:1000px;
  }
  p{
    font-size:20px;
  }
  
  /*Sticky Style Properties*/
  .sticky {
    position: fixed;
    top: 0px;
    width: 100%;
  }
</style>
<div class="header-text">
  <h2>Sticky Navbar</h2>
  <h3>Scroll down here to see sticky navbar </h3>
</div>
<nav id='nav'>
  <ul>
    <li><a href='#home'>Home</a></li>
    <li><a href='#contact'>Contact</a></li>
    <li><a href='#contact'>About Us</a></li>
  </ul>
</nav>
<div class='container'>
  <h1>Sticky Navigation Bar on Scroll Using JavaScript</h1>
  <p>It was going to rain. The weather forecast didn't say that, but the steel plate in his hip did. He had learned over the years to trust his hip over the weatherman. It was going to rain, so he better get outside and prepare.</p>
  <p>The alarm went off and Jake rose awake. Rising early had become a daily ritual, one that he could not fully explain. From the outside, it was a wonder that he was able to get up so early each morning for someone who had absolutely no plans to be productive during the entire day.</p>
</div>
<script>
  window.onscroll = function(){
    stickyFunction();
  };

  var navbar = document.getElementById("nav");
  var navbarOffset = navbar.offsetTop;

  function stickyFunction() {
    if (window.pageYOffset > navbarOffset) {
    navbar.classList.add("sticky");
    } else {
    navbar.classList.remove("sticky");
    }
  }
</script>
</body>
</html>
Try it Yourself

Live Demo