Sling Academy
Home/JavaScript/Creating a Dropdown Menu with Vanilla JavaScript

Creating a Dropdown Menu with Vanilla JavaScript

Last updated: December 12, 2024

Creating a dropdown menu is a fundamental skill in web development. Whether you're a beginner or an experienced developer, understanding how to create a dropdown menu using just vanilla JavaScript (without relying on any libraries like jQuery) is crucial. This article will guide you through building a basic dropdown menu and enhancing it with interactivity.

Understanding the Basics

A dropdown menu typically consists of a button that, when clicked, reveals a list of items beneath it. These items can be links to other pages, or actions executed on the current page. Here’s an example structure for a dropdown menu in HTML:

<div class="dropdown">
  <button class="dropdown-toggle">Menu</button>
  <div class="dropdown-menu">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

This HTML creates a basic structure with a button and a series of links inside what we call a dropdown container. However, to make this work, some styles and JavaScript are needed.

Basic Styling

To give the dropdown menu proper appearance, adding some CSS styles is essential:

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

.dropdown-menu {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

.dropdown-menu a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

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

With this CSS, the dropdown menu is hidden by default (due to display: none;), and styled to give it a basic appearance when visible. The position: absolute; ensures it appears right below its parent.

Adding Interactivity with JavaScript

To make the dropdown toggler functional, you need to write some JavaScript to handle the click event. When the button is clicked, the dropdown items should either appear or disappear:

document.querySelector('.dropdown-toggle').addEventListener('click', function() {
  var dropdownMenu = document.querySelector('.dropdown-menu');
  if (dropdownMenu.style.display === 'none' || dropdownMenu.style.display === '') {
    dropdownMenu.style.display = 'block';
  } else {
    dropdownMenu.style.display = 'none';
  }
});

This JavaScript code identifies the dropdown button and listens for click events. When the button is clicked, it toggles the dropdown-menu's display property between none and block, effectively showing or hiding the menu.

Improving the Dropdown: Adding Event Listeners for Usability

To further enhance usability, you can add functionality to close the dropdown menu if a user clicks outside of it:

window.onclick = function(event) {
  if (!event.target.matches('.dropdown-toggle')) {
    var dropdowns = document.getElementsByClassName('dropdown-menu');
    for (var i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.style.display === 'block') {
        openDropdown.style.display = 'none';
      }
    }
  }
}

This code snippet listens for clicks on the entire window. When anything other than the dropdown button is clicked, the dropdown menu gets closed. This functionality is essential for any dropdown to function well in practical scenarios.

Conclusion

Dropdown menus are a versatile and essential component of modern web design. Creating one using vanilla JavaScript provides a good understanding of how events and DOM manipulation work – fundamental skills for any web developer. Although JavaScript libraries can simplify creating dropdowns, knowing how to implement them manually empowers developers to craft bespoke solutions tailor-made to their unique requirements.

Next Article: Element Positioning: Reading offsetTop and offsetLeft in JavaScript

Previous Article: Building a Simple Tabs Interface Using Only the JavaScript DOM

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration