Skip to content

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.

Every interactive UI component on the web uses some version of this workflow:

  1. Find an elementquerySelector
  2. Listen for an actionaddEventListener
  3. Change a classclassList.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.

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.

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.

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.

In the menu toggle pattern, which technique shows or hides the menu?
Why is it useful to let CSS handle show/hide rather than setting style.display directly in JS?
What does classList.contains('open') return?
Which three JavaScript tools did you combine in this lesson?