Dropdown menus
Part of the JavaScript in Action section of Coddy's HTML journey — lesson 15 of 27.
Dropdown menus are UI components that reveal additional options when triggered. They're commonly used in navigation to organize content without taking up too much space.
First, let's create the HTML structure for a basic dropdown:
<div class="dropdown">
<button class="dropdown-toggle">Menu</button>
<div class="dropdown-menu">
<a href="#">Option 1</a>
<a href="#">Option 2</a>
<a href="#">Option 3</a>
</div>
</div>Now, let's add the JavaScript to toggle the dropdown visibility:
// Get the dropdown toggle button
const dropdownToggle = document.querySelector('.dropdown-toggle');
// Get the dropdown menu
const dropdownMenu = document.querySelector('.dropdown-menu');
// Add click event listener to the toggle button
dropdownToggle.addEventListener('click', function() {
// Toggle the 'show' class on the dropdown menu
dropdownMenu.classList.toggle('show');
});Finally, add some basic CSS to hide/show the dropdown menu:
.dropdown-menu {
display: none;
}
.dropdown-menu.show {
display: block;
}When you click the "Menu" button, the dropdown menu will appear. Clicking it again will hide the menu.
Challenge
EasyCreate a dropdown menu that shows/hides when a button is clicked.
Steps:
- In HTML:
- Add an
onclickattribute to the button that calls a function namedtoggleDropdownwhen clicked
- Add an
- In JavaScript:
- Create a function called
toggleDropdown - Inside the function, toggle the "show" class on the element with ID “myDropdown”
- Create a function called
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Save the Forests</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<h1>Save the Forests</h1>
<p>Even planting one or two trees makes a difference.</p>
</header>
<div class="dropdown">
<button class="dropbtn">Learn More ▼</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Why forests matter</a>
<a href="#">How to grow a tree</a>
<a href="#">Community projects</a>
</div>
</div>
<main>
<section>
<h2>Why Trees Are Important</h2>
<p>
Forests clean our air, give us oxygen, and are home to countless animals.
Each tree you plant helps fight climate change and supports life on Earth.
</p>
</section>
<section>
<h2> Start Small</h2>
<p>
Don’t wait for a big change. Start with just one or two trees in your yard or community.
Your small action inspires others!
</p>
</section>
</main>
<footer>
<p> Together we can make the planet greener.</p>
</footer>
<script src="script.js"></script>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.