I am using the library micromodal.js to handle the functionality of my (accessible) modal dialogs.
Having read recommendations about a11y best practices, I have learned that the modal should get a tabindex="-1"
in order to "trap" the tabbing user (or screen reader) in the modal dialog.
One of the modals I am using it for has scrollable content section. In order to facilitate the content to be focusable and therefore scrollable by arrow keys, I added tabindex="0"
to the section.
On mobile devices it is not the content that should be scrollable, but the whole modal.
The issue that this solution creates is: when opening the modal on smaller screens, the content is focussed first (due to tabindex of 0 being larger than tabindex of -1, I guess?) and the whole header of the modal is not visible.
The desired behavior is that the modal header is visible when it opens. How could I achieve that with still providing an accessible UX?
Code example: https://codepen.io/AstiV/pen/vYKopNZ
First of all, you need to review carefully the difference between tabindex=0 and tabindex=-1. Setting tabindex=0 means that the element is focusable, both manually with tab key and automatically via script. Setting element to tabindex=-1 means that only a script can set focus on it, while it isn't possible to focus the element manually.
Knowing this, you should understand what you did wrong. The most obvious solution would be to focus the element with tabindex=-1 when your modal is shown. If for any reason it's much more logical to have the element with tabindex=0 focused when the modal is opened, then you may first focus the element with tabindex=-1, wait for a short while (50-100ms), and then focus the element with tabindex=0.
Concerning scroll, normally, focusing any element (with whatever tabindex or none) should automatically bring it into view it it isn't yet visible, but if is already visible then the scroll shouldn't change. So even by focusing the element with tabindex=-1 and then the one with tabindex=0, the element with tabindex=-1 should stay visible.