Build a Modal Dialog

Combine the modal layout you built in CSS Positioning with JavaScript that opens it and — crucially — closes it. Two listeners, one bug to fix.

Step 1 of 3

Two events: open and close

The structure is now familiar: a backdrop, a dialog, a close button. The behaviour is two listeners:

  • The 'open' button click → add a class (or remove a hidden attribute) that makes the modal visible.
  • The 'close' button click and the backdrop click → hide it again.

For accessibility, real modals also trap focus inside the dialog, return focus to the opener on close, and handle Escape. HTML's native <dialog> element provides those behaviours for free, but writing a basic version yourself first is excellent practice.

Web Standard

Production modals should use the native <dialog> element (.showModal() / .close()). It ships focus-trap, Escape handling, and modality semantics for free. Hand-rolled div modals miss most of that without extra work.

Learn more on MDN