Skip to content

Commit

Permalink
Generalize focus trap
Browse files Browse the repository at this point in the history
  • Loading branch information
otacke authored Oct 20, 2024
1 parent 9a0ae98 commit 523e0b4
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/scripts/services/focus-trap.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,11 @@ export default class FocusTrap {

return Array.from(container.querySelectorAll(focusableElementsSelector))
.filter((element) => {

return (
element.disabled !== true &&
element.getAttribute('tabindex') !== '-1'
element.getAttribute('tabindex') !== '-1' &&
this.isElementVisible(element)
);
});
}
Expand Down Expand Up @@ -182,6 +184,8 @@ export default class FocusTrap {
return; // we only care about the tab key
}

this.currentFocusElement = document.activeElement;

event.preventDefault();

const index = this.focusableElements.findIndex((element) => {
Expand All @@ -197,4 +201,22 @@ export default class FocusTrap {
this.currentFocusElement = this.focusableElements[newIndex];
this.currentFocusElement.focus();
}

/**
* Check whether element is visible.
* @param {HTMLElement} element Element to check.
* @returns {boolean} True, if element is visible, false otherwise.
*/
isElementVisible(element) {
if (!element) {
return false;
}

const style = window.getComputedStyle(element);
if (style.display === 'none' || style.visibility === 'hidden') {
return false;
}

return element.parentElement ? this.isElementVisible(element.parentElement) : true;
}
}

0 comments on commit 523e0b4

Please sign in to comment.