Putting It Together
As a designer, you’ve probably looked at a hamburger menu and thought: “How does clicking one button make a list of links appear?” The answer is simpler than you’d expect — and you already know all the pieces. This lesson is about snapping them together into something real.
The Pattern: Three Tools, One Result
Section titled “The Pattern: Three Tools, One Result”Every interactive UI component on the web uses some version of this workflow:
- Find an element —
querySelector - Listen for an action —
addEventListener - Change a class —
classList.toggle
That’s it. A tab switcher, a modal dialog, an accordion, a theme toggle — all of them follow this same rhythm. Once you understand it here, you can apply it anywhere.
Building a Menu Toggle
Section titled “Building a Menu Toggle”We’re going to build a nav menu that opens and closes when a button is clicked. Here’s the key insight: JavaScript only toggles a class. CSS does the actual showing and hiding. This is the clean, professional way to build interactions — keep visual logic in CSS, and behavioral logic in JS.
Walking Through the Code
Section titled “Walking Through the Code”Here’s what each part does:
Lines 1–2 grab references to the button and the nav using querySelector. Think of these as giving the elements names so JavaScript can talk to them.
Line 4 sets up a click listener on the button. Every time someone clicks it, the function runs.
Line 5 calls classList.toggle('open'). If the menu doesn’t have the open class, it adds it. If it does have it, it removes it. One line — done.
Lines 6–10 check whether the menu is now open or closed, then update the button label so it always says the right thing. This is good practice: your UI should reflect its current state.
Over in the CSS, .menu starts with display: none. When the open class is added, .menu.open kicks in with display: flex — and the nav appears. When the class is removed, the nav disappears again. JavaScript never touches display directly; that’s CSS’s job.
You Just Built What the Pros Build
Section titled “You Just Built What the Pros Build”That’s not a simplification. Open the source code of almost any production website and you’ll find this exact pattern: a button, a class toggle, and CSS handling the rest. Frameworks like React and Vue abstract over it, but the underlying idea is identical.
The three tools you combined here — querySelector, addEventListener, classList.toggle — are the foundation of frontend interactivity. Everything else is built on top of them.