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.
Part of Adding interactivity
- Introducing Javascript
- Your first Javascript program
- Variables
- Conditional logic
- Affecting the page
- Making a menu
- Responding to user actions
- Keep your Javascript accessible
- Get confident with Javascript
- Add interactivity to your prototypesP