I'm looking for a code that can help me with sticky header for hyva themes.
2 Answers
Since it is on hyva, you can use TailwindCSS
classes on the <header>
tag.
Add the following classes: sticky top-0 z-10
.
The z-10
can be increased/decreased based on your page since it only brings the block forward to avoid having another block covering the header.
This can be done by extending the template file app/design/frontend/[vendor]/[Theme] Magento_Theme::layout/default.xml
:
<body>
<referenceContainer name="header.container" htmlClass="page-header sticky top-0 z-10"/>
</body>
Here is my working code example. It's also eliminated jerking of sticky header!!
<script>
window.onscroll = function() {
showDesktopMenu()
};
function showDesktopMenu() {
let header = document.querySelector('#header'); //main header div
let navbar = document.querySelector('.desktop-navbar'); // child div of main header div
let body = document.querySelector('body'); // document body
if (window.pageYOffset > header.getBoundingClientRect().height) {
navbar.classList.add('sticky-custom');
body.style['padding-top'] = navbar.getBoundingClientRect().height + "px";
} else {
body.style['padding-top'] = "0px";
navbar.classList.remove('sticky-custom');
}
}
</script>
<style>
.sticky-custom {
position: fixed;
z-index: 9999;
width: 100%;
top: 0;
}
</style>