How to make header fixed on scroll in theme

0

HI guys, In this quick tutorial I will show you how we can make any Header sticky. It will work with any theme. And we dont need any plugin as well.

The main task here is to grab the ID or CLASS of our header section, which we want to make sticky.

You can grab it by inspecting the element.

Just right click on your header then choose “Inspect “.

Find the ID or CLASS of your header from the inspect panel.

Now we have our ID of our header. Lets say the ID is ‘header_top’.

Our next step will be to insert some CSS and jQuery codes in our code editor.

First open your theme’s JS editor. You can also use a plugin called “Simple Custom CSS and JS” It will help you easily to insert your code in your theme.

Here is the JS code.

jQuery(document).ready(function() {
  var NavTop = jQuery('#header_top').offset().top;
  var Nav = function() {
    var scrollTop = jQuery(window).scrollTop();
    if (scrollTop > NavTop) { 
      jQuery('#header_top').addClass('sticky');
    } else {
     jQuery('#header_top').removeClass('sticky'); 
    }
  };
 
Nav();
 
  jQuery(window).scroll(function() {
    Nav();
  });
});

What the code does is, if you scroll down a bit. It adds a class to our header div called ‘sticky’ . If we scroll back again to the top it will automatically remove the class.
Perfect! Now lets add some CSS to our ‘sticky’ class.

.sticky{
  width: 100%;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
    right: 0 !important;
        max-width:1440px; margin: 0 auto;  z-index: 99999;
    -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  -o-transition: all .5s ease;
  transition: all .5s ease;
     
}

We have made the header 100% width. You can set a custom width as well. Then we have make the ‘sticky’ class ‘fixed’ positioned with top 0 , left and right 0.
Finally we have added a ‘transition’ so that we can get a nice animation as well.
That’s it, see how easy it is.

Here are all the codes combined
jQuery(document).ready(function() {
  var NavTop = jQuery('#header_top').offset().top;
  var Nav = function() {
    var scrollTop = jQuery(window).scrollTop();
    if (scrollTop > NavTop) { 
      jQuery('#header_top').addClass('sticky');
    } else {
     jQuery('#header_top').removeClass('sticky'); 
    }
  };
 
Nav();
 
  jQuery(window).scroll(function() {
    Nav();
  });
});

.sticky{
  width: 100%;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
    right: 0 !important;
        max-width:1440px; margin: 0 auto;  z-index: 99999;
    -webkit-transition: all .5s ease;
  -moz-transition: all .5s ease;
  -o-transition: all .5s ease;
  transition: all .5s ease;
     
}

Share this post

Share on facebook
Share on twitter
Share on linkedin
Share on pinterest

Leave a Reply

Close Menu
This website uses cookies to provide you with the best service. By using our website, you agree to use the cookie. Learn More