Lesson 2 of 8

Modal dialog

Goal

Focus stays inside the dialog

01

Explanation

Most dialogs that developers build themselves have an obvious flaw: when the user opens one, focus stays on the page behind it, and pressing Tab moves through elements they can't see.

The <dialog> element solves all of this without a single extra line. Its showModal() method traps focus inside the dialog, blocks everything behind it and lets Escape close it. Then, when it closes, the element hands focus back to whatever had it before, so you don't have to write that yourself.

Note that show() is not the same as showModal(). The first opens a regular dialog that doesn't trap focus, has no backdrop and doesn't close with Escape, and mixing the two up is the most common mistake people make with this element.

That leaves two things for you. First, move focus to something useful inside the dialog after it opens. Second, listen for the close event, because it fires whether the dialog was closed with the button or with Escape, so you write what happens on close once instead of twice.

A note on grading: the preview frame is sandboxed for security, and the close event doesn't reach inside it, so the checks here only test what has a visible effect: how the dialog opens, where focus goes, how it closes and the backdrop. Still, write the close listener, because it's the right way to do it and you'll need it on any real page.

02

Your task

Open the dialog with showModal(), move focus inside it, write open in #log when it opens, and style the backdrop with ::backdrop.

Checks

7 checks
  1. The dialog starts closed
  2. Clicking opens it as a modal that traps focus
  3. Focus moves inside it
  4. The close button closes it
  5. The log shows "open" when it opens
  6. The backdrop is styled with ::backdrop
  7. Opening and closing work more than once
03

Hints

0/3
Track lessons0 of 8 done

Build from scratch, on your own, the components you'll find on almost every website, such as tabs, dialogs, tables, toasts and a carousel.

Advanced level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/7

Press “Run and check” to grade your code.

7 checks listed under “Your task”.

Track lessons0 of 8 done

Build from scratch, on your own, the components you'll find on almost every website, such as tabs, dialogs, tables, toasts and a carousel.

Advanced level, 8 lessons, 2 hours in total.