modal.config.mjs 1.28 KB
Newer Older
1
2
export function createModalJail(modal) {
  // add all the elements inside modal which you want to make focusable
ransome1's avatar
ransome1 committed
3
  const focusableElements = '[tabindex]:not([tabindex="-1"])';
4
5
6
  const firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal
  const focusableContent = modal.querySelectorAll(focusableElements);
  const lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal
7
8
9

  firstFocusableElement.focus();

10
11
  document.addEventListener("keydown", function(event) {
    let isTabPressed = event.key === "Tab" || event.keyCode === 9;
12
13
14
    if (!isTabPressed) {
      return;
    }
15
    if (event.shiftKey) { // if shift key pressed for shift + tab combination
16
17
      if (document.activeElement === firstFocusableElement) {
        lastFocusableElement.focus(); // add focus for the last focusable element
18
        event.preventDefault();
19
20
21
22
      }
    } else { // if tab key is pressed
      if (document.activeElement === lastFocusableElement) { // if focused has reached to last focusable element then focus first focusable element after pressing tab
        firstFocusableElement.focus(); // add focus for the first focusable element
23
        event.preventDefault();
24
25
26
27
      }
    }
  });
}