Skip to content
Sticky Navigation Bar

Sticky Navigation Bar On Scroll Using JavaScript

In this tutorial we will check how we can create sticky navigation bar using JavaScript. And the solution for this very easy using vanilla JavaScript.

Lets start with creating some HTML structure. Which have Nav followed by the list item and anchor tags.

Before going through following code check this video which have demo how sticky navigation will work

<nav>
    <a href="#" class="logo">Logo</a>
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Service</a></li>
        <li><a href="#">Product</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</nav>

<div class="background-banner">
    <h1>Sticky Navigation Finish</h1>
</div>

Create CSS file style.css and add following css in that.

*{
    margin:0;
    padding:0;
    box-sizing: border-box;
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
}

body{
    background:#000;
    font-size: 16px;
    height: 200vh;
}

nav{
    position: fixed;
    top:0;
    left:0;
    transition: 0.6s;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 20px 40px;
}

a{
    text-decoration:none;
}

.logo{
    color:#fff;
    font-size: 24px;
    text-transform: uppercase;
}

nav.sticky{
    background-color:#fff;
}

nav.sticky .logo,
nav.sticky ul li a{
    color: #000000;
}

nav ul{
    display: flex;
}

nav ul li{
    list-style: none;
    margin:0px 20px;
}

nav ul li a{
    color:#fff;
    text-transform: uppercase;
}

.background-banner{
    background-image: url(bg.jpg);
    height: 200vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

.background-banner h1{
    color: #fff;
    font-size: 60px;
}

And Last which is final and most important script. Without this your above work not look goods. Now time to create one script.js file or add at the top of the HTML in head section.

<script>
    window.addEventListener('scroll', function(){
        var nav = document.querySelector('nav');
        nav.classList.toggle('sticky', window.scrollY > 0);
    });    
</script>