Focus-Trapped Dialog

A modal dialog that traps Tab, closes on Escape, and returns focus to the button that opened it.


Focus-Trapped Dialog


Use the native dialog element. showModal() opens it on the top layer, closes it on Escape, and gives you a backdrop. The script keeps Tab inside the panel and sends focus back to the opener.

Pair it with the command palette when the dialog is a keyboard-first surface.

HTML

<button type="button" id="openDialog">Edit project</button>
<dialog id="projectDialog" aria-labelledby="dialogTitle">
  <form method="dialog">
    <h2 id="dialogTitle">Rename project</h2>
    <label>Name <input name="name" value="Cursor kit" /></label>
    <div class="dialog-actions">
      <button value="cancel">Cancel</button>
      <button value="save">Save</button>
    </div>
  </form>
</dialog>

CSS

#projectDialog {
  border: 0;
  border-radius: 16px;
  padding: 1.5rem;
  max-width: 24rem;
}
#projectDialog::backdrop { background: rgba(12, 10, 8, 0.55); }
.dialog-actions { display: flex; justify-content: flex-end; gap: 0.5rem; margin-top: 1rem; }

JavaScript

const dialog = document.getElementById("projectDialog");
const openButton = document.getElementById("openDialog");

function focusable() {
  return [...dialog.querySelectorAll("a[href], button, input, textarea, select, [tabindex]:not([tabindex='-1'])")]
    .filter((el) => !el.disabled);
}

openButton.addEventListener("click", () => {
  dialog.showModal();
  focusable()[0]?.focus();
});

dialog.addEventListener("keydown", (event) => {
  if (event.key !== "Tab") return;
  const items = focusable();
  const first = items[0];
  const last = items[items.length - 1];
  if (event.shiftKey && document.activeElement === first) {
    event.preventDefault();
    last.focus();
  } else if (!event.shiftKey && document.activeElement === last) {
    event.preventDefault();
    first.focus();
  }
});

dialog.addEventListener("close", () => openButton.focus());

method="dialog" makes Cancel and Save close the dialog and set dialog.returnValue. Do not trap focus if the dialog is non-modal (show() instead of showModal()).