Μετάβαση στο κύριο περιεχόμενο
← 📄 HTML & the platform·Ενότητα A5 · Μάθημα 9
ΕργασίαBuild a dialog that uses showModal (NOT show) so Tab is correctly trapped inside. <dialog id='m'><h2>Hi</h2><button>OK</button></dialog>. Open it programmatically.

Παγίδες πληκτρολογίου: η καρτέλα κολλάει σε ένα modal

75 XP7 min
Θεωρία

What's a keyboard trap

A user opens a modal with the keyboard. They press Tab repeatedly to navigate. After 5 Tabs, focus exits the modal and lands on a button BEHIND it — but they can't see it (modal still covers the page) and Tab now navigates the dimmed page. They're stuck.

This is a WCAG 2.1.2 failure — "No Keyboard Trap."

The native <dialog> solution

<dialog id="cookies">
  <h2>Cookies</h2>
  <button>Accept</button>
  <button>Decline</button>
</dialog>

<script>
  document.querySelector("#cookies").showModal();
</script>

When you call .showModal() (not .show()), the browser:

  1. Traps Tab focus inside the dialog.
  2. Sends ESC to close the dialog (you don't need a JS listener).
  3. Makes everything OUTSIDE the dialog inert — invisible to focus AND screen readers.

Free keyboard accessibility. The custom-modal alternative (<div role="dialog"> + manual focus trap + manual ESC handler) is ~100 lines of JS and a common source of bugs.

When you can't use <dialog>

Older browser support — use inert on the page wrapper + a focus-trap library (or roll your own). But for green-field projects in 2026, just use <dialog>.

Don't trap in non-dialogs

A <div> that traps Tab and ISN'T a modal is a bug. Tab should always be able to leave content that isn't the focused widget.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.