How To Make On Scroll Shrink Navigation Menu

In this article, we will show how to make on scroll shrink navigation menu. Our HTML file will contain a navigation bar and some paragraph. In order to show how the code works.
How the code works:

See the Pen on scroll shrink nav by focusoncode (@focuson_Code) on CodePen.

The most important part of the code in the HTML file is our navigation bar, which contains:
Menu links
Social media

The code:

<div class="header" id="nav_head">
            <div id="logo">
        <a href="#"><img id="img_logo" src=""></a>
            <div class="nav" id="navbar">
                    <li><a href="#" id="active">Home</a></li>
                   <li><a href="#">Hot Deals</a></li>
                   <li><a href="#">Vehicles</a></li>
                   <li><a href="#">Faqs</a></li>
                   <li><a href="#">Features</a></li>
                   <li><a href="#">Contact</a></li>
                   <div class="social" id="social_media">
                   <li><a href="" target="_blank"><i class="fa fa-facebook-square" ></i></a></li>
                   <li><a href="" target="_blank"><i class="fa fa-instagram"  ></i></a></li>
                   <li><a href="" target="_blank"><i class="fa fa-google-plus-square" ></i></a></li></div>
                 <li><button onclick="myFunction()" class="icon" >
    <i class="fa fa-bars"></i>

In order to make the navigation bar sticky, we will use position property. We will set its value to sticky. A sticky element toggles between relative and fixed, depending on the scroll position.

 .header {
  width: 100%;
  display: inline-flex;
  background-color: white;
    transition: 0.4s;
    position: sticky;
  top: 0;
  z-index: 99;


Now to make on scroll animation we will need to use some javascript. This function tells the browser that when we are scrolling down more than 80px the style of some elements will be this else they will have the default style.

 window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    document.getElementById("navbar").style.lineHeight= "3.8";
    document.getElementById("navbar").style.fontSize= "17px";
    document.getElementById("logo").style.maxWidth = "110px";
  } else {
    document.getElementById("navbar").style.fontSize= "20px";
    document.getElementById("navbar").style.lineHeight = "5";
    document.getElementById("logo").style.maxWidth = "200px";

Leave a reply