Create a header that appears and disappears by scrolling

akimon658

Akimo

Posted on April 27, 2022

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
💖 💪 🙅 🚩
akimon658
Akimo

Posted on April 27, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What is an Responsive Web Design?
javascript What is an Responsive Web Design?

February 5, 2024

Error Boundaries in React
react Error Boundaries in React

November 18, 2023

Lazy Loading in React
react Lazy Loading in React

November 18, 2023