Menu
Coddy logo textTech

Dropdown

Part of the JavaScript in Action section of Coddy's HTML journey — lesson 4 of 27.

The dropdown component is a common UI element that reveals additional content when clicked.

Start by creating the HTML structure for a dropdown:

<div class="dropdown">
  <button class="dropdown-toggle">Select an option</button>
  <div class="dropdown-menu">
    <a href="#">Option 1</a>
    <a href="#">Option 2</a>
    <a href="#">Option 3</a>
  </div>
</div>

Add some basic CSS to style the dropdown:

.dropdown {
  position: relative;
  display: inline-block;
}
.dropdown-menu {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  z-index: 1;
}
.show {
  display: block;
}

Now, add JavaScript to toggle the dropdown menu:

const dropdownToggle = document.querySelector('.dropdown-toggle');
const dropdownMenu = document.querySelector('.dropdown-menu');

dropdownToggle.addEventListener('click', function() {
  dropdownMenu.classList.toggle('show');
});

When the button is clicked, the JavaScript adds or removes the 'show' class, which controls the visibility of the dropdown menu.

challenge icon

Challenge

Easy

Your task:

  1. Add the third option called “Logout” with class logout into the dropdown menu.
  2. Complete the click event listener by adding the line that toggles the "show" class on the dropdown menu.

Try it yourself

<!DOCTYPE html>
<html>
<head>
  <title>Dropdown Challenge</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <h2>Welcome to the Dashboard</h2>
  <p>Click the button below to open your profile menu:</p>

  <div id="profileDropdown" class="dropdown">
    <button class="dropdown-toggle">
      My Profile
    </button>
    <div class="dropdown-menu">
      <a href="#">View Profile</a>
      <a href="#">Settings</a>
    </div>
  </div>

    <script src="script.js"></script>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in JavaScript in Action