Keep Focus Inside a Modal
Write the code, see it run, pass the checks.
The problem
- medium
- Code
- Pro
The page shows "Name: Ada" and two buttons, "Edit name" and "Help". "Edit name" opens a modal dialog, rendered only while it's open: an element with role="dialog" and aria-modal="true", named by its heading "Edit name" through aria-labelledby. It holds a text input labelled "Name", filled with the current name, then "Save" and "Cancel" buttons. When it opens, focus moves to the Name input. While it's open, Tab and Shift+Tab cycle inside it: Tab from Cancel goes back to the Name input, and Shift+Tab from the Name input goes to Cancel. Save closes it and updates the line, Cancel or Escape closes it without changing anything, and every way of closing puts focus back on the "Edit name" button. The starter already opens the dialog and closes it with Save and Cancel; the focus handling, the labelling and Escape are up to you.
Your code must pass
- Opening it focuses the Name input, in a dialog named "Edit name"
- Tab and Shift+Tab stay inside the dialog
- Escape and Cancel close it and return focus to "Edit name"
- Save updates the name and returns focus