Fixed Header when Scroll (jQuery).
/* Fixed Header when Scroll
==================================== */
/*
*** HTML file ***
<header id="header">
<div class="nav-container" id="nav-container">
...
</div>
</header>
*** CSS file ***
.nav-container.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 200;
}
*/
/* JS file
========================*/
// know the height of the header tag
var headerHeight = $("#header").height();
// know the height of the nav-container
var navHeight = $("#nav-container").innerHeight();
// pluggable event listener to the document
$(document).on("scroll", function() {
// find out the current height of the top
var documentScroll = $(this).scrollTop();
// conditions to display nav
if(documentScroll > headerHeight) {
// add the class fixed
$("#nav-container").addClass("fixed");
// add extra height header
$("#header").css({
"paddingTop": navHeight
});
} else {
// remove the class fixed
$("#nav-container").removeClass("fixed");
// remove extra height header
$("#header").removeAttr("style");
}
});