mmenu tutorial

Fire the plugin

Now that we have created a .html file, included all needed .css and .js files and set up the markup for the page and the menu, we can fire the mmenu.js plugin. Most commonly, you'd write the JavaScript in a separate .js file, but for this tutorial we'll write it in an inline <script>.

Remember the ID "menu" on the <nav>? We're now using it to target the menu.

<script>
    document.addEventListener(
        "DOMContentLoaded", () => {
            new Mmenu( "#menu" );
        }
    );
</script>

Options

The mmenu.js plugin provides a set of options for customizing your menu. The default option values can be overridden by passing new values to the method.

For example, lets set the slidingSubmenus option to false so all submenus will expand below their parent instead of come sliding in from the right.

<script>
    document.addEventListener(
        "DOMContentLoaded", () => {
            new Mmenu( "#menu", {
                slidingSubmenus: false
            });
        }
    );
</script>

For a complete overview of all options, check out the options and add-ons pages.

Open the menu

The plugin automatically binds a click event that opens the menu to every <a> that targets the menu in its href attribute. So lets add one in the header.

<div id="header">
    <a href="#menu">Open the menu</a>
</div>

Open the menu manually

If you're not using an <a> but some other element, for example a <button>, or if you need to open the menu programatically, you can invoke the open method from the API to open the menu manually.

<script>
    document.addEventListener(
        "DOMContentLoaded", () => {
            const menu = new Mmenu( "#menu" );
            const api = menu.API;

            document.querySelector( "#open-button" )
                .addEventListener(
                    "click", () => {
                        api.open();
                    }
                );
        }
    );
</script>

Close the menu

By default, the menu automatically closes when clicking on the still visible part of the page. The plugin also automatically binds a click event that closes the menu to every <a> that targets the "page" in its href attribute.

Remember the ID "page" on the <div>? We're now using it to target the "page".

<a href="#page">Close the menu</a>

Close the menu manually

If you're not using an <a> but some other element, for example a <button>, or if you need to close the menu programatically, you can invoke the close method from the API to close the menu manually.

<script>
    document.addEventListener(
        "DOMContentLoaded", () => {
            const menu = new Mmenu( "#menu" );
            const api = menu.API;

            document.querySelector( "#close-button" )
                .addEventListener(
                    "click", () => {
                        api.close();
                    }
                );
        }
    );
</script>