Headers can be animated easily by CSS and a few JavaScript, but the speed will be constant. I hate that, so I’ll create a header that works naturally like this.
Sample code & Demo
This script changes the value of top
by scrolling.
const header = document.querySelector("header"),
headerStyle = window.getComputedStyle(header),
headerHeight = parseFloat(headerStyle.height);
let lastPosition = 0;
document.addEventListener("scroll", () => {
const currentPosition = window.scrollY,
diff = currentPosition - lastPosition;
let newTop = parseFloat(headerStyle.top) - diff;
if (diff < 0) {
newTop = Math.min(newTop, 0);
} else {
newTop = Math.max(newTop, 0 - headerHeight);
}
header.style.top = `${newTop}px`;
lastPosition = currentPosition;
});
If your header has a shadow, you also need to calculate that.
newTop = Math.max(newTop, 0 - headerHeight - shadowHeight)
Top comments (0)