UNIT 24 • STAGE 7 OF 7
window.scrollY and the scroll event that brings the header to life
The browser fires a scroll event every time the user scrolls the page. Inside the event handler, you can read window.scrollY, a number that tells you how many pixels the page has been scrolled from the top.
The pattern is straightforward: if scrollY is greater than a threshold (say, 80 pixels, roughly the height of the hero's top padding), add the .scrolled class. If it is at or below the threshold, remove it. CSS handles the visual change.
Add a second <script> block just before </body>, after your existing tab switcher script:
window.scrollY is a number. When the page is at the very top, it is 0. As you scroll down, it increases. At 80px down, your condition becomes true.classList.add('scrolled') adds the class to the header element. The CSS rule .site-header.scrolled immediately activates, no re-rendering needed.classList.remove('scrolled') removes it when the user scrolls back up. The CSS transition handles the smooth animation back to transparent.handleScroll() called once at the end: this handles the case where the page is loaded mid-scroll (e.g., after a browser refresh). Without this, the header would start transparent even if the page is already scrolled down.Scroll the live preview up and down. At the top, the header should be transparent, showing the hero behind it. As soon as you scroll past 80px, the background should fade in smoothly. Scroll back to the top: it fades back out.
This is the same pattern used on most modern restaurant, portfolio, and product websites. You have built it from scratch.
Manoomin Kitchen is live. You have a full restaurant website with a design system, a working tab-switching menu, a two-column about section, a reservation form, and a scroll-triggered fixed header.
The two JavaScript skills from this unit, the tab switcher and scroll handler, are patterns you will see and use throughout your career. You now know how they work at the source level.