2

I am using Magento 2.1.5 and I need to make header sticky for the frontend. how can I make header sticky?

When user scroll page then header should be sticky at the top, how we can do this? this code should apply for desktop view only not for a mobile and iPad view.

Thanks in advance.

2
  • i tried but not working in magento 2 – Utsav IIHGlobal May 12 '17 at 7:58
  • Linked answer is for Magento 1.9, but this question is for Magento 2.1., so it shouldn't be marked as duplicate – kovinet Dec 13 '19 at 15:45
5

You can add this piece of javascript code to your custom.js file and you can call this custom.js file either in default_head_blocks.xml or requirejs-config.js

require([ "jquery" ], function($){

$(window).scroll(function () {
    if( $(window).scrollTop() > $('#header').offset().top && !($('#header').hasClass('sticky'))){
    $('#header-2').addClass('sticky');
    } else if ($(window).scrollTop() == 0){
    $('#header').removeClass('sticky');
    }
});
});

and then add some css to this sticky class like this

#header.sticky {
    background: #fff none repeat scroll 0 0;
    border-bottom: 4px solid #325052;
    margin: 0 auto;
    max-width: 100%;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 99;
}

Hope this helps!

7
  • i used with "default_head_blocks.xml" to add custom js but its giving error as below : ReferenceError: $ is not defined $(window).scroll(function () { also i tried replacing "jQuery" with "$" but error still come – Utsav IIHGlobal May 12 '17 at 9:50
  • Your custom.js should be like this:require([ "jquery" ], function($){//your code goes here}); – Sejal Shah May 12 '17 at 10:32
  • @UtsavIIHGlobal did you manage to get the sticky header working ? – Sejal Shah May 15 '17 at 6:34
  • still same error.. sorry – Utsav IIHGlobal May 15 '17 at 11:28
  • Can you post the code and the error? If it is showing the same error, your code is not updated in pub/static file. You can deploy the content and check again. – Sejal Shah May 15 '17 at 11:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.