DEV Community

Akimo
Akimo

Posted on • Originally published at akimon658.github.io on

Create a header that appears and disappears by scrolling

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.

Search result screen of Google images

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;
});
Enter fullscreen mode Exit fullscreen mode

If your header has a shadow, you also need to calculate that.

newTop = Math.max(newTop, 0 - headerHeight - shadowHeight)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)