Crazy-Unicooorn / crazy-guessr

Your comprehensive training hub for improving at GeoGuessr.
https://crazy-unicooorn.github.io/crazy-guessr/
3 stars 1 forks source link

[Training Modal] Prevent keyboard navigation behind the modal #41

Closed Crazy-Unicooorn closed 12 months ago

Crazy-Unicooorn commented 12 months ago
  const modifiedElements = useRef(new Set<Element>());

  useEffect(() => {
    const focusableElements = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
    const modalOpen = document.getElementById("modal");

    if (displayModal) {
      const elements = document.querySelectorAll(focusableElements);
      elements.forEach((el: Element) => {
        if (!modalOpen?.contains(el)) {
          el.setAttribute("tabindex", "-1");
          modifiedElements.current.add(el);
        }
      });
    } else {
      modifiedElements.current.forEach((el: Element) => {
        el.removeAttribute("tabindex");
      });
      modifiedElements.current.clear();
    }
  }, [displayModal]);