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.
-
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 ?Juan Ignacio– Juan Ignacio2020年10月06日 19:36:02 +00:00Commented Oct 6, 2020 at 19:36
2 Answers 2
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.
-
Can you provide exact path ? I add in the header.phtml. but its not working for mePraful– Praful2019年11月16日 10:55:35 +00:00Commented Nov 16, 2019 at 10:55
-
<your_theme>/Magento_theme/templates/html/header.phtml . If you do not have this file, override it.MichaelHa– MichaelHa2019年11月16日 10:57:56 +00:00Commented Nov 16, 2019 at 10:57
-
please accept my answer to helps other dev.MichaelHa– MichaelHa2019年11月16日 11:14:13 +00:00Commented Nov 16, 2019 at 11:14
-
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.