Modal 1.1
This allows us to show an accessible and customisable modal window.
Modal windows are shown when an element with the class js-modal__trigger
is clicked. Each of these triggers is tied to a particular modal window via one of two ways:
1. View an href
attribute, assuming it is pointing to the id of a modal window (e.g. href="#modal-example"
).
2. If no appropriate href
attribute is present, via an aria-controls
attribute that contains the value of the modal window's id
attribute.
Modal windows can be closed by clicking outside the window (i.e. on the overlay between it and the content), by clicking the "close button", or by pressing the "escape" key.
Focus is automatically moved inside the modal window when it is opened, kept inside it while it is opened (tabbing through elements wraps within the modal window), and returned to the appropriate element when the modal window is closed.
Please note several attributes in the example markup are necessary for the modal window to be accessible, such as the role
and aria-labelledby
attributes. For more information, see the WAI-ARIA Authoring Practices page's "dialog" section.
A function to be called when a modal window is shown can be passed in via an options object to the init
method.
The onShow callback receives the modal Element being shown as an argument.
This code also uses a pubsub implementation to subscribe to two events:
/modal/show
can be published to show a modal window of a specified ID.
When a modal is open, a class is applied to the <body>
tag, which can be used to apply CSS for purposes like hiding the main scrollbar when a full screen modal is open.
By default, this class is modal__body-open
, but it can be customised for a specific modal via the data attribute data-modal-body-open-class
on the js-modal
element.
Required. Activate is used for accessible event binding, so elements other than <button>
can be used as modal triggers.
Optional. If present, adds support for pubsub events.
To support using position: fixed;
alongside CSS transforms to centre a modal window, the size of the body is set explicitly to be an even number of pixels. This prevents CSS transforms moving the element by a fractional number of pixels, causing it to become blurry.
If there is no JavaScript, the :target
CSS pseudo-class is used to show and hide modal windows depending on the current hash. Using a
tags with role="button"
and appropriate href
attributes for both trigger and close button is necessary to support this. Otherwise, they can use button
tags if support for no JavaScript is not necessary.
You can put any markup within the body of a modal.
See the WAI-ARIA specification for how an accessible modal window should be implemented.