htmlintermediatemitFeatured
Mobile Menu
A hamburger menu that expands a drawer.
2.1k758438148
About this module
A responsive header with a hamburger button that toggles a slide-down mobile menu with proper ARIA.
#nav#mobile#hamburger#drawer
Source code
Installation
- 1
Create the files
Create `index.html`, `style.css` and (if listed) `script.js` in the same folder.
- 2
Paste the code
Copy each file's source into its matching file.
- 3
Open in the browser
Open `index.html` in any modern browser.
Usage
- 1
Copy the HTML
Paste the markup where you need it.
<link rel="stylesheet" href="style.css" /> <script src="script.js"></script> <header class="mh-mobile-nav"> <span class="mh-brand">✦ Acme</span> <button class="mh-burger" aria-expanded="false" aria-controls="mh-menu" aria-label="Open menu"> <span></span><span></span><span></span> </button> <nav id="mh-menu" class="mh-drawer" aria-label="Mobile"> <a href="#">Product</a> <a href="#">Pricing</a> <a href="#">Docs</a> <a href="#">Blog</a> <a class="mh-cta" href="#">Get started</a> </nav> </header> - 2
Wire up the script
Include `script.js` before the closing body tag.
const burger = document.querySelector(".mh-burger"); const drawer = document.getElementById("mh-menu"); const onToggle = (open) => { burger.setAttribute("aria-expanded", String(open)); drawer.classList.toggle("open", open); drawer.setAttribute("aria-hidden", String(!open)); }; burger.addEventListener("click", () => onToggle(!drawer.classList.contains("open"))); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && drawer.classList.contains("open")) onToggle(false); }); drawer.addEventListener("click", (e) => { if (e.target.tagName === "A") onToggle(false); });