Skip to content

Instantly share code, notes, and snippets.

@phortuin
Last active May 24, 2023 07:55
Show Gist options
  • Save phortuin/c5ea7410f9515828f4c9b32c097027bd to your computer and use it in GitHub Desktop.
Save phortuin/c5ea7410f9515828f4c9b32c097027bd to your computer and use it in GitHub Desktop.
Simple mobile menu

If you don’t run any other JavaScript on your site but need a mobile menu, this will do the trick. Simple media queries make sure the menu button shows up on large screens only, and the navigation menu is hidden from small screens. By progressively enhancing the nav element with a data-menu attribute, the button toggles visibility of the menu.

HTML:
/nav.html

CSS: /styles.css

JS: /menu.js

Note that I didn’t take accessibility into account, and if JavaScript is disabled on small screens, your website visitors won’t have any way to navigate :)

(function() {
const qs = query => document.querySelector(`[data-${query}]`)
const click = (el, listener) => el.addEventListener('click', listener)
window.addEventListener('DOMContentLoaded', () => {
const menu = qs('menu')
click(qs('menu-button'), () => menu.classList.toggle('xs-hidden'))
})
}())
<button class="l-hidden" data-menu-button>
menu
</button>
<nav class="xs-hidden" data-menu>
<ol>
<li>
<a href="/">Home</a>
</li>
</ol>
</nav>
@media (max-width: 767px) {
.xs-hidden {
display: none;
}
}
@media (min-width: 768px) {
.l-hidden {
display: none;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment