Creating a Hamburger Menu (JavaScript)

While CSS-only hacks exist, the industry standard way to create an expandable mobile "hamburger" menu is to use a small snippet of JavaScript alongside your HTML and CSS.

When the user clicks the hamburger button, the JavaScript function simply adds an active class to the menu element. When clicked again, it removes that class. Your CSS dictates how that active class looks.

The HTML Structure

Unlike the checkbox hack, we can use a highly semantic and accessible structure when using JavaScript to provide the menu functionality. We use a standard button for our hamburger icon and an unordered list (ul) for the links. Be sure to give them both an id so JavaScript can find them:

The CSS Styling

In our CSS media query, we hide the links by default using display: none;. The next step is creating an .active class that restores the display property. This class won't be on the HTML by default; JavaScript will handle that:

The JavaScript Logic

Finally, we add our JavaScript inside a script tag at the bottom of the page. This script listens for a click event on the button, and toggles the active class on the menu:

Full Working Example

Below is the complete, interactive layout. Try resizing your browser window until you see the hamburger icon, then click it to watch the JavaScript toggle the CSS class:

View Output Full Screen Preview

Tip: Accessibility First

Using a button for interactive elements is always preferred over using a random div or span. Buttons are naturally keyboard-navigable and immediately recognized by screen readers as interactive controls.