Skip to content

Instantly share code, notes, and snippets.

@nocodesupplyco
Created December 19, 2022 16:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nocodesupplyco/04c4487b589408a9dc4d6b56ac5765a8 to your computer and use it in GitHub Desktop.
Save nocodesupplyco/04c4487b589408a9dc4d6b56ac5765a8 to your computer and use it in GitHub Desktop.
Accessible Modal
<!-- Example HTML structure of button and modal -->
<a modal="button" class="button cc-primary">Open Modal</a>
<div class="modal-wrapper" role="dialog" aria-modal="true" aria-labelledby="Popup Modal">
<div class="modal-container">
<div class="p-2">
<h3>This is a modal</h3>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</p>
<a href="#" class="button cc-primary">Button</a>
<a href="#" class="modal-close_btn">
<span class="sr-only">Close Modal</span>
<span aria-hidden="true">×</span>
</a>
</div>
</div>
<div tabindex="-1" aria-hidden="true" class="modal-close_area"></div>
</div>
$(function() {
var findDialog = function (elem) {
var tabbable = elem.find('select, input, textarea, button, a').filter(':visible');
var firstTabbable = tabbable.first();
var lastTabbable = tabbable.last();
/*set focus on first input*/
firstTabbable.focus();
/*redirect last tab to first input*/
lastTabbable.on('keydown', function (e) {
if ((e.which === 9 && !e.shiftKey)) {
e.preventDefault();
firstTabbable.focus();
}
});
/*redirect first shift+tab to last input*/
firstTabbable.on('keydown', function (e) {
if ((e.which === 9 && e.shiftKey)) {
e.preventDefault();
lastTabbable.focus();
}
});
/* allow escape key to close insiders div */
elem.on('keyup', function (e) {
if (e.keyCode === 27) {
document.querySelector('.modal-close_btn').click();
};
});
};
$('[modal=button]').click(function (e) {
e.preventDefault();
$(this).next().show();
findDialog($(this).next());
});
$('.modal-close_btn, .modal-close_area').click(function (e) {
e.preventDefault();
$('.modal-wrapper').hide();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment