Search code examples
javascriptmaterial-designmaterial-componentsmaterial-components-webmdc-components

Prevent MDC Menu from closing after clicking first menu item


We are using MDC menu component. I am looking for a way to not close the menu when clicked on the first item in the menu.

I tried applying a class to mdc-list-item and specifying cursor as auto, but it is not working.

.menu-do-not-close {
   cursor: auto !important;
}

below is the example fiddle

https://jsfiddle.net/phani25485/Lt6q2gxa/2/

Could you provide some direction on how to achieve this.


Solution

  • You can stop the menu from closing after a specific item is selected by calling event.stopPropagation() on the mdc-list-item click event when the event target has a specific class assigned. You will need to add some additional code to handle the list item click event since this prevents the normal MDC menu click handling.

    const menu = mdc.menu.MDCMenu.attachTo(document.querySelector('.mdc-menu'));
    document.querySelector('.mdc-button').addEventListener('click', () => {
      menu.open = !menu.open;
    });
    
    //Prevent menu close when option with 'prevent-menu-close' class clicked
    for (const option of document.querySelectorAll('.mdc-list-item')) {
      option.addEventListener('click', (event) => {
        const prevent = event.currentTarget.classList.contains('prevent-menu-close');
        if (prevent) {
          event.stopPropagation();
          // handle 'prevent-menu-close' list item click event
        }
      });
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Material Select</title>
        <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
        <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">
        <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
        <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
      </head>
      <body>
        <div class="mdc-menu-surface--anchor">
          <button class="mdc-button">
            <span class="mdc-button__label">Open Menu</span>
          </button>
          <div class="mdc-menu mdc-menu-surface">
            <ul class="mdc-list" role="menu" aria-hidden="true" aria-orientation="vertical" tabindex="-1">
              <li class="mdc-list-item prevent-menu-close" role="menuitem">
                <span class="mdc-list-item__text">Prevent Close</span>
              </li>
              <li class="mdc-list-item" role="menuitem">
                <span class="mdc-list-item__text">Another Menu Item</span>
              </li>
            </ul>
          </div>
        </div>
      </body>
    </html>