net - UK (2020-02)

(Antfer) #1

Modals


STEP 5: TRAP FOCUS
Next, we need to ensure that non-mouse users
remain ‘trapped’ within the modal until they wish to
leave it. Otherwise, they may abruptly ‘unfocus’ from
the modal accidentally, despite it still (undesirably)
blocking the view of the main document.
This is most conveniently handled by the
aria-modal attribute:


...

Although, in cases where aria-modal is not supported,
we need to instead use aria-hidden as a fallback for
describing what is and isn’t focusable when the
modal is and isn’t visible.



...

} else {
...
document.querySelector(“main”).setAttribute(“aria-
hidden”, “true”);
document.querySelector(“#modal”).setAttribute(“aria-
hidden”, “false”);
}


STEP 6: RETURN FOCUS
Finally, when the user is ready to return to the main
document, we need to return focus to the modal’s
trigger, as this is what the user was focused upon
before they triggered the modal.


function closeModal() {
if (typeof modal.close === “function”) {
modal.close(); // removes the open attribute
} else {
modal.classList.remove(“open”); // removes the .open
class
}
trigger.focus();
}


document.querySelector(“#closeModal”).
addEventListener(“click”, function() {
closeModal();
});


Since we’d also want to facilitate easy dismissal,
ensure the modal can be dismissed using the esc key.
This is the default behaviour when the showModal() is
supported, so the following snippet is a fallback:


document.addEventListener(“keydown”, function(event) {
if (event.keyCode == 27) {


closeModal();
}
}, true);
This also works:
<dialog>
<form method=”dialog”>
<button>Close</button>
</form>
<dialog>

STEP 7: SCREEN READER ALERTS
The <dialog> element requires an aria-label attribute
and value so screen readers can announce how
the user interface has changed for those with
visual impairments, although aria-labelledby (https://
netm.ag/33GjTkt) works fine too. The value of aria-label
is only announced once the modal is visible.
In cases where <dialog> is not supported, the
role=”alertdialog” attribute works as a fallback. Without
it being present, the value of aria-label will be
completely ignored.

<dialog role=”alertdialog” aria-label=”Please do
something”></dialog>

Now try it for yourself!

Top Styling the modal is
super easy when <dialog>
is supported
Above aria-label is being
communicated by Apple
VoiceOver
Free download pdf