mmenu

How to close mmenu programmatically on click of submenu item?


As the headline says, I can't reaaly close menu per code.

My submenu items are anchor links of the parent element like site#anchor

I want to close the menu after click on the anchorlink, if I'm on that page.

i tried it this way but its not working correctly

menu.querySelectorAll('.level_2 a').forEach(bindClick);
            
function bindClick(item){
  if (item.href.substring(item.href.lastIndexOf('/')).indexOf(pathname) >= 0){
    let hash = item.getAttribute("href");
                    
    item.addEventListener("click", () => {
      scroll({
    top: document.querySelector(hash).offsetTop - document.getElementById('header_bottom').clientHeight,
        behavior: "smooth"
      });
      api.close();
    });
  }
}    

The menu closes but the background of the menu doesnt disappear.

What am I missing?


Solution

  • Try the below code.

    menu.querySelectorAll('.level_2 a').forEach(bindClick);
    
    function bindClick(item) {
      if (item.href.substring(item.href.lastIndexOf('/')).indexOf(pathname) >= 0) {
        let hash = item.getAttribute("href");
        enter code here
        item.addEventListener("click", (event) => {
          event.preventDefault(); // Prevent the default link behavior
    
          scroll({
            top: document.querySelector(hash).offsetTop - document.getElementById('header_bottom').clientHeight,
            behavior: "smooth"
          });
    
          // Close the menu programmatically
          var menuElement = document.querySelector("#your-menu-selector"); // Replace with your menu selector
          // Close the menu using the appropriate method based on the menu library you're using
          // For example, if you're using the menulibrary, you can use:
          menuElement. menu.close();
    
          // If you're using a different menu library, refer to its documentation for the correct close method
        });
      }
    }
    

    Note: In this code, after performing the desired action (in this case, scrolling), the menu is closed programmatically. You'll need to replace "#your-menu-selector" with the correct selector for your menu element.

    The specific method to close the menu programmatically will depend on the menu library you're using. The code snippet assumes you're using the menu library. If you're using a different library, make sure to refer to its documentation for the appropriate method to close the menu programmatically.