htmladvancedmit

Modal Dialog

An accessible modal with focus trap basics.

2.6k1.1k540450

About this module

A centered modal with overlay, Escape-to-close and focus management — the foundation of any dialog UX.

#modal#dialog#overlay

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>
    <button class="mh-open">Open modal</button>
    <div class="mh-overlay" hidden>
      <div class="mh-modal" role="dialog" aria-modal="true" aria-labelledby="mh-title">
        <div class="mh-modal-head">
          <h2 id="mh-title">Confirm deletion</h2>
          <button class="mh-x" aria-label="Close">×</button>
        </div>
        <p>This action cannot be undone. Are you sure?</p>
        <div class="mh-modal-actions">
          <button class="mh-cancel">Cancel</button>
          <button class="mh-delete">Delete</button>
        </div>
      </div>
    </div>
  2. 2

    Wire up the script

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

    const open = document.querySelector(".mh-open");
    const overlay = document.querySelector(".mh-overlay");
    const close = () => { overlay.hidden = true; open.focus(); };
    const show = () => {
      overlay.hidden = false;
      overlay.querySelector(".mh-x").focus();
    };
    open.addEventListener("click", show);
    overlay.addEventListener("click", (e) => { if (e.target === overlay) close(); });
    overlay.querySelector(".mh-x").addEventListener("click", close);
    overlay.querySelector(".mh-cancel").addEventListener("click", close);
    document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !overlay.hidden) close(); });
    
Overview
Categorycomponents
Frameworkhtml
Difficultyadvanced
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