A sticky header helps keep your navigation bar visible at the top of the page when users scroll down. Using a small jQuery snippet, you can easily create a smooth and responsive sticky header effect.
Below is a simple and effective jQuery script that adds a fixed class to the header after scrolling 250px. It also adjusts the next element’s padding to prevent layout shifting.
$(window).scroll(function(){
if ($(this).scrollTop() > 250) {
$('#header').addClass("fixed");
$('#header+*').css('padding-top', $('#header').outerHeight() + 'px');
}else{
$('#header').removeClass("fixed");
$('#header+*').css('padding-top', '0');
}
});
#header {
width: 100%;
transition: all 0.3s ease;
}
#header.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 999;
background: #fff;
box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}