Animate a Glassmorphic Header on Scroll using Next.JS 12 and Tailwind CSS

In this tutorial, I am going to show you how you can do the same. Let’s jump right into it.
Demo
Setup
Creating a Next app with TailwindCSS
I am going to use tailwind for the basic stylings needed in the app
npx create-next-app next-tailwind-header-animation -e with-tailwindcss
Creating the index page content
I am creating a very stylish card with tailwind
So let’s replace the index.js
by the content below
run the command below to lanch server
npm run dev
Here the preview of the page 😍😍

Creating the Header
Create a new file Header.js
in the components
folder.
I’m creating an Array that contain the menu sections (easy 😉)
Now let’s Add the Header inside the index.js
let’s jump to http://localhost:3000

It’s looks amazing ✌️
Adding Magical code to allow header be animated on scroll
Create a state to hold if we need to change the background or not.
const [animateHeader, setAnimateHeader] = useState(false);
Setting the state based on scroll-
useEffect(() => {
const listener = () => {
if (window.scrollY > 140) {
setAnimateHeader(true);
} else setAnimateHeader(false);
};
window.addEventListener("scroll", listener); return () => {
window.removeEventListener("scroll", listener);
};
}, []);
You might need to change the value for scrollY based on your app needs.
Here the final Header.js
import { useState, useEffect } from “react”;
import Link from “next/link”;export default function Header() {
const [animateHeader, setAnimateHeader] = useState(false);
useEffect(() => {
const listener = () => {
if (window.scrollY > 140) {
setAnimateHeader(true);
} else setAnimateHeader(false);
};
window.addEventListener(“scroll”, listener); return () => {
window.removeEventListener(“scroll”, listener);
};
}, []); const menuItems = [
{ title: “Home”, url: “https://themeptation.net" },
{ title: “Products”, url: “https://themeptation.net" },
{ title: “Contact”, url: “https://themeptation.net" }
];return (
<header
className={`w-full backdrop-filter backdrop-blur-lg bg-white/50 fixed z-10 trasition ease-in-out duration-500 ${
animateHeader && "shadow-xl"
}`}
>
<div className="max-w-7xl mx-auto ">
<div
className={`flex max-w-screen-xl py-10 ${
animateHeader && "py-5"
} mx-auto items-center justify-between px-8 trasition ease-in-out duration-500`}
>
<a
href="https://themeptation.net"
className="text-xl font-bold tracking-tighter text-indigo-400 pr-8"
>
Themeptation
</a>
<nav>
<ul className="flex items-center justify-start">
{menuItems?.map((item) => (
<li key={item?.title}>
<Link href={item?.url}>
<a className="px-2 lg:px-6 py-6 text-md border-b-2 border-transparent hover:border-indigo-400 leading-[22px] md:px-3 text-gray-400 hover:text-indigo-500">
{item?.title}
</a>
</Link>
</li>
))}
</ul>
</nav>
</div>
</div>
</header>
);
}
Here the final code of the tutorial
Chime in and leave your thoughts and suggestions in the comments below.