Search code examples
webmaterial-componentsmaterial-components-web

MDC-Web: Multiple simple menu


I use google MATERIAL COMPONENTS FOR THE WEB and have problems with the "Simple Menu". Check my codepen: [Multiple menus per page?][1]

[1]: https://codepen.io/QJan84/pen/govRmg

The first menu works, the others do not. What do I have to do to have multiple menus per page?


Solution

  • You’re using document.querySelector for menu and toggle, but it will return only the first node elements matching “.mdc-simple-menu” and “.js--toggle-dropdown” respectively.

    Instead, you should use document.querySelectorAll that will return the NodeList, which you’ll need to convert to array to iterate with its elements.

    I wrapped your example menus and toggles into containers for selecting toggles easier with Node.parentElement.

    So, the final result might look like this:

    const menuEls = Array.from(document.querySelectorAll('.mdc-simple-menu'));
    
    menuEls.forEach((menuEl) => {
      // Initialize MDCSimpleMenu on each ".mdc-simple-menu"
      const menu = new mdc.menu.MDCSimpleMenu(menuEl);
    
      // We wrapped menu and toggle into containers for easier selecting the toggles
      const dropdownToggle = menuEl.parentElement.querySelector('.js--dropdown-toggle');
      dropdownToggle.addEventListener('click', () => {
        menu.open = !menu.open;
      });
    });
    

    You can view the demo on Codepen.