How to Create Sticky Header with Animation in Magento 2?

How to add a custom Js file?

To write jQuery code, we should add a custom Js file. If you have already added a Js file, skip this step.

Add default_head_blocks.xml file in app/design/frontend/<vendor>/<theme>/Magento_Theme/layout/

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<script src="js/custom.js" />
</head>
</page>

Add custom.js file in app/design/frontend/<vendor>/<theme>/web/js/

Content for JS:

requirejs(['jquery'], function( $ ) {
$(window).scroll(function () {
//variables    
var getHeaderHeight = $('.page-header').innerHeight(); 
var scroll = $(window).scrollTop();
if(scroll >= getHeaderHeight) {
$(".page-header").addClass("sticky active");
} 
else 
{
$(".page-header").removeClass("sticky active");
}
}); 
});

How to Add CSS/LESS File?

Update in LESS file

Add code in _extend.less file in app/design/frontend/<vendor>/<theme>/web/css/source/

Content of _extend.less:

.page-wrapper {
.page-header.sticky.active {
position: fixed;
z-index: 999;
background: #fff;
width: 100%;
box-shadow: 0px -5px 11px rgba(0,0,0,.5);
animation: scroll .3s ease-in-out;
}
}
@keyframes scroll {
from {
top: -100%;
}
to {
top: 0px;
}
}

Update in CSS file:

How to Add CSS file?

Add default_head_blocks.xml file in app/design/frontend/<vendor>/<theme>/Magento_Theme/layout/

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<script src="js/custom.js" /> 
<css src="css/custom.css" />
</head>
</page>

Add code in custom.css file in app/design/frontend/<vendor>/<theme>/web/css/

.page-wrapper .page-header.sticky.active {
position: fixed;
z-index: 999;
background: #fff;
width: 100%;
box-shadow: 0px -5px 11px rgba(0,0,0,0.5);
animation: scroll .3s ease-in-out;
}
@keyframes scroll {
from {
top: -100%;
}
to {
top: 0px;
}
}

Leave a comment

Your email address will not be published. Required fields are marked *