Skip to content

Instantly share code, notes, and snippets.

@jeromeabel
Created April 21, 2023 14:12
Show Gist options
  • Select an option

  • Save jeromeabel/941da71f8d0bacf191fc2b8a845b886b to your computer and use it in GitHub Desktop.

Select an option

Save jeromeabel/941da71f8d0bacf191fc2b8a845b886b to your computer and use it in GitHub Desktop.

ARIA Modal

Ref

Code

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();
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment