DEV Community

Cover image for A11y tips: how to manage focus inside modals
Carlos Espada
Carlos Espada

Posted on

A11y tips: how to manage focus inside modals

To handle the focus in a modal in an accessible way, the same steps must always be followed, no matter how complex the modal that we are showing is:

  1. We show the modal when the user activates the button that opens it
  2. We immediately bring the focus to the button to close the modal, or in case to its first <input> if it had them. Never to an element other than these two.
  3. From there, the user has to be able to handle the focus in a circular way through the elements of the modal without leaving them. Once you reach the last element, you have to start over with the first one, the focus cannot go to elements that are behind the modal since the user would lose the reference of where they are.
  4. To exit the modal, the user can click the close button or the Esc key, which we will make it work by hiding the modal.
  5. Once closed, the focus must return to the place where the user left the navigation before displaying the modal, that is, to the button that opened it.

On the W3C website there are examples of how to do this, and Scott O'Hara has written a very good article that explains in detail how to make modals accessible.

Top comments (0)