How to Build a Dropdown Menu with JavaScript

Dropdown menus are a common design pattern found on many websites and web applications. They allow you to present a list of navigation options or actions to the user in a compact, collapsible format. When clicked, the menu expands to display the full list of choices, and collapses again when an item is selected or the menu is closed.

Implementing a dropdown menu can be achieved with HTML, CSS, and JavaScript. In this in-depth tutorial, we‘ll walk through the process of building a dropdown menu step-by-step. By the end, you‘ll have a fully functional dropdown that is accessible and easy to customize.

Step 1: Create the HTML Structure

The first step is to set up the HTML elements that will make up the dropdown menu. We‘ll need a button to toggle the menu open and closed, and a container for the list of menu items.

<div class="dropdown">
  <button class="dropdown-toggle" id="dropdownMenu">
    Dropdown Menu
    <i class="fas fa-caret-down"></i>
  </button>
  <div class="dropdown-menu" id="dropdownList">
    <a href="#" class="dropdown-item">Option 1</a>
    <a href="#" class="dropdown-item">Option 2</a>
    <a href="#" class="dropdown-item">Option 3</a>
  </div>
</div>

The outer <div> with class dropdown acts as a container for the entire component. Inside it, the <button> will function as the clickable toggle to show and hide the menu. The <i> tag adds a down arrow icon to visually indicate the presence of a dropdown.

The inner <div> with class dropdown-menu will contain the list of options. Each <a> tag represents a menu item. You can customize the text and links as needed for your use case.

We‘ve also given the button and menu id attributes of dropdownMenu and dropdownList respectively. This will allow us to easily select these elements with JavaScript later.

Step 2: Style with CSS

With the basic structure in place, we can use CSS to style the appearance of the dropdown and define its initial state. By default, we want the menu to be hidden until the user clicks the button.

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-toggle {
  padding: 10px;
  border: none;
  background-color: #f1f1f1; 
  cursor: pointer;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  display: none;
  background-color: white;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  list-style: none; 
  padding: 0;
  margin: 0;
  min-width: 150px;
}

.dropdown-menu.show {
  display: block;
}

.dropdown-item {
  display: block;
  padding: 10px;
  color: black;
  text-decoration: none;
}

.dropdown-item:hover {
  background-color: #f1f1f1;
}

Key things to note:

  • The .dropdown container is set to position: relative. This allows the absolutely positioned menu to be positioned relative to the container.
  • The .dropdown-menu is initially hidden with display: none. It is positioned absolutely below the button with top: 100%.
  • The .show class sets display: block on the menu. This class will be toggled with JavaScript to show/hide the menu.
  • The menu items have some padding and hover styles for better visual feedback.

Here‘s what it looks like with these styles applied:

[Demo GIF of styled dropdown]

Step 3: Toggle Menu Visibility with JavaScript

Now we can use JavaScript to toggle the visibility of the dropdown menu when the button is clicked. We‘ll also add some extra functionality to close the menu when clicking outside of it.

// Get the necessary elements
const dropdownButton = document.getElementById(‘dropdownMenu‘);  
const dropdownMenu = document.getElementById(‘dropdownList‘);

// Toggle dropdown visibility when button is clicked
dropdownButton.addEventListener(‘click‘, function(e) {
  e.preventDefault();
  dropdownMenu.classList.toggle(‘show‘);
});

// Close dropdown when clicking outside the menu
document.addEventListener(‘click‘, function(e) {
  if (!e.target.matches(‘.dropdown-toggle‘) && !e.target.closest(‘.dropdown-menu‘)) {
    dropdownMenu.classList.remove(‘show‘);
  }
});

First, we get references to the button and menu elements using document.getElementById and the id attributes we defined in the HTML.

Then we attach a click event listener to the button. When clicked, it calls a function that toggles the show class on the menu element using classList.toggle. This alternates the menu between visible and hidden states.

To close the menu when clicking outside of it, we can listen for clicks on the entire document. If a click occurs and the clicked element is not the button or the menu, we remove the show class to hide the menu. The closest method is used to check if the clicked element is inside the menu.

With this JavaScript in place, the dropdown menu is now fully functional! Clicking the button will show and hide the menu, and clicking outside will close it.

[Demo GIF of functional dropdown]

Step 4: Closing Menu with Keyboard

For better accessibility, we should also allow users to close the dropdown menu using the keyboard. Specifically, pressing the Escape key or Enter key while the menu is focused should close it.

// Close dropdown with Escape key
document.addEventListener(‘keydown‘, function(e) {
  if (e.key === ‘Escape‘) {
    dropdownMenu.classList.remove(‘show‘);
  }  
});

// Close dropdown when menu item is selected
dropdownMenu.addEventListener(‘keydown‘, function(e) {
  if (e.key === ‘Enter‘) {
    e.preventDefault();
    e.target.closest(‘.dropdown-item‘).click();
    dropdownMenu.classList.remove(‘show‘);
  }
});

The first event listener checks for the Escape key being pressed while the menu is open. If so, it removes the show class to hide the menu.

The second listens for the Enter key being pressed while a menu item is focused. It prevents the default behavior, simulates a click on the focused item, then closes the menu.

Accessibility Considerations

When building dropdown menus, there are some important accessibility considerations to keep in mind:

  • The button element should have a meaningful text label so screen reader users know what it does
  • The menu should be keyboard accessible, with focus managed properly
  • ARIA attributes like aria-haspopup and aria-expanded should be used to communicate state to assistive technology

Here‘s our HTML with these attributes added:

<div class="dropdown">
  <button class="dropdown-toggle" id="dropdownMenu" aria-haspopup="true" aria-expanded="false">
    Dropdown Menu
    <i class="fas fa-caret-down"></i>
  </button>
  <div class="dropdown-menu" id="dropdownList" role="menu" aria-labelledby="dropdownMenu">
    <a href="#" class="dropdown-item" role="menuitem">Option 1</a>
    <a href="#" class="dropdown-item" role="menuitem">Option 2</a>
    <a href="#" class="dropdown-item" role="menuitem">Option 3</a>
  </div>  
</div>

And we can update the aria-expanded attribute with JavaScript when toggling the menu:

dropdownButton.addEventListener(‘click‘, function(e) {
  e.preventDefault();
  dropdownMenu.classList.toggle(‘show‘);

  // Toggle aria-expanded attribute
  const expanded = this.getAttribute(‘aria-expanded‘) === ‘true‘;
  this.setAttribute(‘aria-expanded‘, !expanded);
});

Extending the Functionality

There are many ways you can extend and enhance the basic dropdown menu we‘ve built. A few ideas:

  • Add keyboard navigation to the menu items with the up/down arrow keys
  • Animate the opening/closing of the menu with CSS transitions
  • Allow for nested submenus to create a hierarchical navigation
  • Trigger the menu on hover instead of click
  • Position the menu based on available space (e.g. open upwards if not enough room below)
  • Create an accessible multi-select dropdown

Feel free to experiment and customize the code we‘ve written to fit your specific needs. The fundamental concepts can be easily adapted to a variety of use cases and designs.

Putting It All Together

Here‘s the complete code for our accessible dropdown menu:

[Insert final code snippets for HTML, CSS, and JS]

With this code in place, you have a solid foundation for a dropdown menu that is keyboard accessible, screen reader friendly, and easily customizable.

Building user interface components like this from scratch is a great way to sharpen your front-end development skills. It requires the combination of semantic HTML, CSS layouts and styles, and JavaScript behaviors to create something that looks good and functions well for all users.

I hope this in-depth tutorial has given you a clear understanding of how to build a dropdown menu with JavaScript. Now it‘s your turn – try implementing one in your own projects!

As always, feel free to reach out with any questions. Happy coding!

Similar Posts