BETAThis is a new service – your feedback will help us to improve it.

Making a menu

On narrow mobile screens, it's common practice to hide menus behind a button. When the user taps or clicks the button, the menu will be displayed.

If the user activates the button again, the menu hides again.

Consider the following HTML:

<button id="menu-toggle">Menu</button>

<nav id="main-menu" hidden>
  <ul>
    <li>
      <a href="#">Products</a>
    </li>
    <li>
      <a href="#">About</a>
    </li>
    <li>
      <a href="#">Contact us</a>
    </li>
  </ul>
</nav>

We have a button, and a menu.

We are going to hide the menu by default, and include a class which, when applied using Javascript, will show the menu. We can hide it visually with the following CSS:

#main-menu{
  display: none;
  visibility: hidden;
}

.visible{
  display: block !important;
  visibility: visible !important;
}

In a previous module, we considered CSS specificity, and how some CSS will override other CSS. Normally, CSS attached to an ID like main-menu will override that attached to a class.

We've used !important on both of the values in our visible class, to ensure they will override all others.

Adding the class

We can use similar code to the previous lesson to show this menu:

const menu = document.querySelector("#main-menu")
const button = document.querySelector("#menu-toggle")

button.addEventListener("click", function(){
	menu.classList.add("visible")
})

This looks different than the previous lesson because the user is interacting with one element, but affecting a second element.

When the button is clicked, the menu should now appear.

Toggling the class

There is currently no way to hide the menu once it's been made visible. We want to be able to click the button a second time and have the menu vanish again.

We can adapt our code to use an if statement.

const menu = document.querySelector("#main-menu")
const button = document.querySelector("#menu-toggle")

button.addEventListener("click", function(){
	if (menu.classList == "visible") {
			menu.classList.remove("visible")
	} else {
			menu.classList.add("visible")
	}
})

Now, we check whether the menu already has the class visible applied to it. If so, we remove it. Else, we add it.

This is not a perfect solution. Can you foresee any problems with this code? Consider users who have Javascript turned off, or users with accessibility issues.

We will address accessibility issues later in this module.

Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Adding interactivity
  1. Introducing Javascript
  2. Your first Javascript program
  3. Variables
  4. Conditional logic
  5. Affecting the page
  6. Making a menu
  7. Responding to user actions
  8. Keep your Javascript accessible
  9. Get confident with Javascript
  10. Add interactivity to your prototypesP