Accessible Modal Dialog Windows

Author: James Braithwaite

Modals dialog windows (sometimes just referred to as modals).

They are easy to do, right?
They are hard to do right.

When a design calls for a modal, it’s all too easy to think ‘that shouldn’t be too difficult, I know a bit off CSS and JS, I can style a box and toggle it with a class. Easy, right?’

Well, yes. But no.

Easy, until real-world content and real-world browser/device sizes come to the party. How best to position the dialog? What if the content overflows the defined size? What if the viewport is small? Suddenly we find ourselves in a soup of conditional formatting, allowing the modal content to scroll, but remembering to fix its primary controls (Accept / Close etc). Chris Coyier covered all these considerations back in 2016.

And these design challenges don’t even begin to consider accessibility.

Recently we came across a small script from Edenspiekermann (the studio behind legendary typographer and designer Eric Spiekermann) that aimed to make modals more accessible.

The markup

At first glance, the expected DOM structure seems excessive. What is all this extra markup? Can’t I do this with one element?

This markup is required to switch the tab focus away from the main document and into the modal dialog. This is important for accessibility as users who rely on tab focus to navigate webpages will find themselves losing focus of the dialog (if they ever gained focus of it in the first place) once they move past the last navigational element within it. They then may not be able to regain focus of the modal. If the modal contained a crucial call-to-action in order to proceed, you would have succeeded in rendering the site inaccessible for those users.

It also releases focus back to the main document when the dialog is closed. The dialog can be closed by clicking anywhere outside of the modal area, or via the close button, or via pressing escape.

Handing Style

By default, the script doesn’t handle any styling, leaving that up to you, based on your needs. In order to get the dialog showing and hiding, you only need the following CSS:

Instantiating the modal

It’s worth noting that if you attempt to instantiate a modal in javascript on a page where the modal element doesn’t exist in the HTML (perhaps you only require the dialog on certain pages, not sitewide) then it will throw an error, so you’ll need to test for the existence of the element first.

The script is a fork of the accessible-modal-dialog by Greg Kraus but (according to Edenspiekermann) has been improved, and the reliance on jQuery removed.

In summary

When designing your interface, consider whether you really need a modal dialog window at all. Can you solve the problem another way? And if you do, hopefully the above  will help you avoid some of the accessibility pitfalls when integrating one into your front-end.