1

I am using Magento2 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. enter image description here

Thanks in advance.

Asad Khan
1,48612 silver badges38 bronze badges
asked Nov 16, 2019 at 5:43
1
  • Do it works in magento 2.3.5 too ? Because it seams there are different folders an structure. Also in back office content- config- header there are a field to add code for the header. Can works if I add there ? Commented Oct 6, 2020 at 19:36

2 Answers 2

5

in header.phtml in your theme add this:

<script type="text/javascript">
require([ "jquery" ], function($){
 $(document).scroll(function () {
 var $window = $(window);
 var windowsize = $window.width();
 var height = $(document).scrollTop();
 if(height > 150 && windowsize >= 768) {
 $('your header class').addClass('fixed-menu');
 }else{
 $('your header class').removeClass('fixed-menu');
 }
 });
});
</script>
<style type="text/css">
 .fixed-menu{ 
 animation-duration: .45s;
 animation-fill-mode: both;
 animation-name: fadeInDown;
 position: fixed;
 z-index: 500;
 width: 100% ;
 top:0;
 border-bottom: 1px solid #ccccb3;
 }
</style>

hope this will helps you.

answered Nov 16, 2019 at 10:40
4
  • Can you provide exact path ? I add in the header.phtml. but its not working for me Commented Nov 16, 2019 at 10:55
  • <your_theme>/Magento_theme/templates/html/header.phtml . If you do not have this file, override it. Commented Nov 16, 2019 at 10:57
  • please accept my answer to helps other dev. Commented Nov 16, 2019 at 11:14
  • yes sure i will do.. Commented Nov 18, 2019 at 9:17
0

You need to add the custom CSS in your stylesheet if its not already there. Here is sample example: https://www.w3schools.com/howto/howto_js_sticky_header.asp Hope this will help? Else comment your link I will share the exact CSS code for you.

answered Nov 16, 2019 at 9:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.