Sticky Header
Make a header stick to the top after scrolling past a threshold, adding a shadow for depth.
Make a header stick to the top after scrolling past a threshold, adding a shadow for depth.
const $header = $("header");
const stickyTop = $header.offset().top;
$(window).on("scroll.sticky", function() {
if ($(this).scrollTop() > stickyTop) {
$header.addClass("sticky").css("top", 0);
} else {
$header.removeClass("sticky");
}
});
/* CSS */
/* header { position: relative; transition: box-shadow 0.2s; }
header.sticky { position: fixed; width: 100%; z-index: 1000; box-shadow: 0 2px 8px rgba(0,0,0,0.15); } */
CSS position: sticky + top: 0 is the pure-CSS alternative — no JavaScript needed for most cases.