jQuery Simple and Accessible Modal Window
This jQuery plugin provides you a shiny and accessible modal window, using ARIA.
A presentation page and demo is here: http://a11y.nicolas-hoffmann.net/modal/ (with styles, etc.)
How it works
Basically, it wraps all the page into a div id="js-modal-page"
, and when you activate one modal, the scripts inserts a dialog
element at the end of your page, adds the noscroll
class on the body
element (to remove scroll with CSS if needed), puts the focus into it and traps focus in the modal window. When you exit it, the focus is given back to the element that opened it.
For mouse users, they can click outside the modal window to close it. For keyboard users, you can strike Esc to close it.
If you never activate a modal window, it won’t be anywhere in the code.
Options and attributes
Simply put class="js-modal" on a button or a link to activate the script.
- Attribute
data-modal-text
: the text of your modal window (will be put into a p tag). - Attribute
data-modal-content-id
: the id of (hidden) content in your page that will be put into your modal window. - Attribute
data-modal-title
: the main title of the modal window. - Attribute
data-modal-close-text
: the text of the close button in your modal window. - Attribute
data-modal-close-title
: the title attribute of the close button in your modal window. - Attribute
data-modal-background-click="disabled"
: disable the possibility to click outside the modal window to close it.
Enjoy.
P.S: this plugin is in MIT license. It couldn't be done without the precious help of @ScreenFeedFr, @sophieschuermans, @johan_ramon, @goetsu and @romaingervois.
Vanilla JS version
Similar version as above but without any jQuery dependency.
Differences
-
page content is not wrapped but every
body > *
element is deactivated when dialog is open -
dialog is reused and only deactivated if closed
-
js-modal
elements are not automatically activated as modals (see next) -
uses
a[href=#...]
if available as modalContentId -
in addition to
data-model-...
options added programmatic option// inits all js-modal elements and use data-attributes as jQuery Version jsModal('.js-modal')
// or add options as api fields jsModal({ selector: '.api-js-modal-button', modalCloseText: 'CLOSE IT! API button', modalCloseTitle: 'CLOSE IT Title', modalTitle: 'Title:', modalContentId: 'content_id' // explicit id })
// minimal setup, uses href hash of link as modalContentId jsModal({ selector: '.api-js-modal-a' })
Styling
Body elements gets a jsmodal-open
class when dialog is opened. This way you can style dialog and content overlay to open with e.g. transitions etc.
See vanilla.html for an example.