Restore the keyboard focus after completing a task or action

Make sure the keyboard focus returns to a predictable spot after completing a task or action (such as closing a modal or menu). The best place to return to is the button that triggered the action in the first place.

One common mistake with keyboard focus handling is that the focus is lost after completing a task. Make sure the keyboard user can predict where the keyboard focus ends up.

If the original control is no longer available (like when a dialog deletes a resource), put yourself in the place of a user and find the best alternative spot. Try to set focus near the original point of focus, so the user doesn’t have to tab all the way from the top of the page to where they were before.

For <dialog> the correct focus management is handled automatically when you invoke the JavaScript method showModal().

How to test for a predictable keyboard focus

  1. Open the component.
  2. Close the component with the available close option.
  3. Check if the focus returns to the button that triggered the action
  4. Also check if the focus returns properly when the component is closed with the Escape key.

Examples

The responsive menu with the WordPress Navigation Block handles the keyboard focus correctly. But always check the keyboard interaction yourself when installing this block on a site.

Resources

WCAG Success Criterion for predictable keyboard focus

Other resources