Skip to content

Keyboard focus and accessibility

Hyvä modals handle keyboard focus and accessibility automatically as much as possible.

Focus shift when showing and hiding dialogs

When a modal is shown, the first focusable element is selected automatically. To specify a different element to be focussed, add the x-focus-first attribute.

<?= $modalViewModel->createModal()->withContent(<<<END_OF_CONTENT
<div class="mt-20 flex justify-between gap-2">
    <button @click="hide" type="button" class="btn">
        {$escaper->escapeHtml(__('Cancel'))}
    </button>
    <button x-focus-first @click="alert('beep')" type="button" class="btn btn-primary">
        {$escaper->escapeHtml(__('I agree'))}
    </button>
</div>

When the modal is hidden, the focus is moved back to the element that triggered the modal.
This also works when opening multiple nested dialogs.

Focus trapping

When a modal with a backdrop is shown, the website elements outside the modal dialog can no longer be focused with Tab / Shift-Tab.

This is accomplished adding the inert attribute to all outer sibling elements and their descendants.

Because browser support is not complete yet, the polyfill library https://cdn.jsdelivr.net/npm/wicg-inert@3.1.1/dist/inert.min.js (3.1kB) is included in Hyvä and loaded on pages where the hyva_modal layout handle is used.
The polyfill library is only loaded when a modal is opened.

For more details please refer to the inert polyfill github repo.

Once all browsers support the attribute the polyfill will be removed.