DEV Community

Discussion on: Create an accessible dropdown navigation

Collapse
 
moopet profile image
Ben Sinclair

I tried this (which is admittedly a bit messy) using relatedTarget on the event to determine whether the link was headed to another menu- or submenu-item. I'm also clearing all the top level focus classes whenever the top level menu is re-focused... it seems to work.

topLevelLinks.forEach(link => {
    if (link.nextElementSibling) {
      link.addEventListener('focus', function() {
        topLevelLinks.forEach(link => {
          link.parentElement.classList.remove('focus');
        });

        link.addEventListener('blur', function(e) {
          link.parentElement.classList.remove('focus');
        });

        this.parentElement.classList.add('focus');
      });

      const subMenu = link.nextElementSibling;
      const subMenuLinks = subMenu.querySelectorAll('a');

      subMenuLinks.forEach(link => {
        const topLevelLink = link.parentElement.parentElement.parentElement;

        link.addEventListener('focus', function() {
          topLevelLink.classList.add('focus');
        });

        link.addEventListener('blur', function(e) {
          if (e.relatedTarget) {
            const targetTopLevelLink = e.relatedTarget.parentElement.parentElement.parentElement;

            if (targetTopLevelLink != topLevelLink) {
              topLevelLink.classList.remove('focus');
            }
          }
        });
      });
    }
  });