htmlintermediatemit

Dropdown Menu

A click-to-open dropdown menu.

6.0k1.5k315325

About this module

A dropdown menu that opens on click with keyboard support and closes on Escape or outside click.

#dropdown#menu#popover

Source code

Installation

  1. 1

    Create the files

    Create `index.html`, `style.css` and (if listed) `script.js` in the same folder.

  2. 2

    Paste the code

    Copy each file's source into its matching file.

  3. 3

    Open in the browser

    Open `index.html` in any modern browser.

Usage

  1. 1

    Copy the HTML

    Paste the markup where you need it.

    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <div class="mh-dropdown">
      <button class="mh-trigger" aria-expanded="false" aria-haspopup="menu" aria-controls="mh-drop">
        Actions <span class="mh-caret">▾</span>
      </button>
      <div class="mh-menu" id="mh-drop" role="menu" aria-hidden="true">
        <button role="menuitem">Edit</button>
        <button role="menuitem">Duplicate</button>
        <button role="menuitem">Share</button>
        <button role="menuitem" class="danger">Delete</button>
      </div>
    </div>
  2. 2

    Wire up the script

    Include `script.js` before the closing body tag.

    const wrap = document.querySelector(".mh-dropdown");
    const trigger = document.querySelector(".mh-trigger");
    const menu = document.getElementById("mh-drop");
    const setOpen = (open) => {
      trigger.setAttribute("aria-expanded", String(open));
      menu.setAttribute("aria-hidden", String(!open));
      wrap.classList.toggle("open", open);
    };
    trigger.addEventListener("click", () => setOpen(!wrap.classList.contains("open")));
    document.addEventListener("click", (e) => {
      if (!wrap.contains(e.target)) setOpen(false);
    });
    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape") setOpen(false);
    });
    
Overview
Categorycomponents
Frameworkhtml
Difficultyintermediate
Licensemit
Versionv1.0.0
Features
  • Keyboard navigable
  • Focus states
  • No dependencies
Traits
  • ResponsiveYes
  • Dark modeYes
  • AccessibleYes
  • Production readyYes
Browser support
  • Chrome 90+
  • Firefox 90+
  • Safari 15+
  • Edge 90+

Related modules

Command Palette

Search modules and jump anywhere