- Yogesh Chavan, How to trap focus inside modal to make it ADA compliant
Used in my project FishEye
// Handle Tab Event to stay in Modal Elements
handleFocus() {
// All the elements inside modal which you want to make focusable
const elementsList = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
const focusableElements = this.$wrapper.querySelectorAll(elementsList);
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
document.addEventListener('keydown', function (e) {
if (e.key !== 'Tab') {
return;
}
// Switch focus when first and last element are reached
if (e.shiftKey) { // Shift + tab combination
if (document.activeElement === firstElement) {
lastElement.focus();
e.preventDefault();
}
} else { // Tab pressed
if (document.activeElement === lastElement) {
firstElement.focus();
e.preventDefault();
}
}
});
firstElement.focus();
}