/accessible-modal.html Secret
Created
December 19, 2022 16:08
Star
You must be signed in to star a gist
Accessible Modal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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