Building an Interactive Website
16. Showing and Hiding a Mobile Menu
A common real-world example is a responsive navigation menu.
On a desktop screen, the navigation links might be visible:
Home About Projects Contact
On a mobile screen, there may not be enough space, so the menu is collapsed behind a button:
☰
When the user clicks the button, JavaScript can show the menu.
When the user clicks it again, JavaScript can hide the menu.
16.1 HTML
A simple structure might look like this:
<nav>
<button id="menu-button">
Menu
</button>
<div id="menu">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Projects</a>
<a href="#">Contact</a>
</div>
</nav>
16.2 CSS
We can initially hide the menu:
#menu {
display: none;
}
Then create a class that makes it visible:
#menu.show {
display: block;
}
The important idea is that CSS controls the appearance, while JavaScript decides when the class should be added or removed.
16.3 JavaScript
First, select the elements:
const menuButton = document.querySelector("#menu-button");
const menu = document.querySelector("#menu");
Then listen for a click:
menuButton.addEventListener("click", () => {
menu.classList.toggle("show");
});
classList.toggle() does exactly what we need:
- If the class does not exist, it adds it.
- If the class already exists, it removes it.
So:
Click
↓
"show" class added
↓
Menu becomes visible
Click again
↓
"show" class removed
↓
Menu becomes hidden
This is a very common pattern in web development.
17. A Complete Simple Menu Example
HTML
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Menu</title>
<style>
#menu {
display: none;
}
#menu.show {
display: block;
}
</style>
</head>
<body>
<button id="menu-button">
Menu
</button>
<nav id="menu">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Projects</a>
<a href="#">Contact</a>
</nav>
<script>
const menuButton =
document.querySelector("#menu-button");
const menu =
document.querySelector("#menu");
menuButton.addEventListener("click", () => {
menu.classList.toggle("show");
});
</script>
</body>
</html>
Open this file in a browser and click the button.
You now have a complete interactive web page using HTML, CSS, and JavaScript.
18. The Relationship Between HTML, CSS, and JavaScript
At this point, it is useful to understand how the three technologies work together.
Think of a web page as three layers.
HTML --- Structure
HTML defines what exists.
<button id="menu-button">Menu</button>
CSS --- Presentation
CSS defines how it looks.
button {
padding: 10px 20px;
}
JavaScript --- Behavior
JavaScript defines what happens.
button.addEventListener("click", () => {
// Do something
});
A simple way to remember this is:
HTML → What is on the page?
CSS → What does it look like?
JavaScript → What does it do?
In real applications, these responsibilities can overlap more than this simplified model suggests, but this is a useful starting point.