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:
- We show the modal when the user activates the button that opens it
- 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.
- 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.
- 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.
- 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.