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 Commented May 12, 2017 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
    Commented Dec 13, 2019 at 15:45

1 Answer 1

6

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 Commented May 12, 2017 at 9:50
  • Your custom.js should be like this:require([ "jquery" ], function($){//your code goes here});
    – Sejal Shah
    Commented May 12, 2017 at 10:32
  • @UtsavIIHGlobal did you manage to get the sticky header working ?
    – Sejal Shah
    Commented May 15, 2017 at 6:34
  • still same error.. sorry Commented May 15, 2017 at 11:28
  • 1
    Thanks @Sejal Shah Its working fine. just one thing i needed to do is. this code will work only for desktop view. not for mobile or ipad view. how can i check for it ? Commented May 24, 2017 at 7:08

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