Skip to content
>GLB_
Go back

50projectsIn50days – Day 25: Sticky Nav

A Sticky menu navigation is popular in webs. It keeps a menu bar at the top of the page visible on the screen while the user scrolls down. Most of the wev development frameworks uses it, or has a solution to achieve this objective. Make an sticky navigation bar in plain javascript is not difficult. There are a lot of tutorials which explain how to create it. It isn’t a novel idea, but it’s useful to learn more about Javascript.

The HTML could be any kind you want. In my case I have a nav bar in the page with the following tags:

    <nav class="nav">      <div class="container">        <h1 class="logo"><a href="/index.html">Sticky Nav</a></h1>        <ul>          <li><a href="#" class="current">Home</a></li>          <li><a href="#">About</a></li>          <li><a href="#">Service</a></li>          <li><a href="#">Contact</a></li>        </ul>      </div>    </nav>

The important part is the “nav” container that has the begining style.

.nav {    position: fixed;    background-color: slateblue;    top: 0;    left: 0;    right: 0;    transition: all 0.3s ease-in-out;}

But, we also have the style which change the sate to active

.nav.active {    background-color: #fff;    box-shadow: 0 2px 10 rgba(0, 0, 0, 0.3);}.nav.active a {    color: #000}.nav.active .container {    padding: 10px 0;}

This changes is made by a javascript code whihc compare the scroll in Y, to the height:

function fixNav(){    if(window.scrollY > nav.offsetHeight + 150) {        nav.classList.add('active')    } else {        nav.classList.remove('active')    }}

You can see the code in this GitHub Repository: 25.sticky_nav and the demo of the project is here: Sticky Nav


Share this post:

Previous Post
50projectsIn50days – Day 26: Vertical Slider
Next Post
Run Redash Locally