metisMenu - Documentation

Introduction

What is metisMenu?

MetisMenu is a jQuery plugin that provides a flexible and responsive multi-level menu component. It’s designed to create elegant and easily navigable menus for websites and applications, particularly useful in sidebars or navigation areas. MetisMenu offers features like collapsible submenus, smooth animations, and support for various customization options, making it a versatile choice for enhancing user interface design.

Key Features

Getting Started

MetisMenu is designed to be easily integrated into your project. Before you begin, ensure you have included the necessary jQuery library in your HTML file. MetisMenu relies on jQuery for its functionality. After including jQuery and the MetisMenu JavaScript file (and optionally the CSS file for styling), you’ll initialize the menu by calling the metisMenu function on the element containing your menu structure.

Installation

MetisMenu can be installed using several methods:

<link rel="stylesheet" href="https://cdn.example.com/metisMenu.css">
<script src="https://cdn.example.com/jquery.min.js"></script>  <!--Ensure jQuery is included first-->
<script src="https://cdn.example.com/metisMenu.js"></script>
npm install metismenu

Then, include it in your project using a module bundler like Webpack or Parcel. Refer to your bundler’s documentation for specific instructions on including npm packages.

Basic Usage

Initialization

After including the necessary jQuery and MetisMenu files (as described in the Installation section), initializing the menu is straightforward. You simply call the metisMenu() function on the root element of your menu structure. This element should typically be an unordered list (<ul>) containing list items (<li>) that represent the menu items.

$(document).ready(function() {
  $('#myMenu').metisMenu();
});

Replace #myMenu with the CSS selector for your menu’s container element. This code snippet ensures the menu is initialized after the DOM is fully loaded.

Markup Structure

Your HTML markup should follow a nested list structure. Each <li> element represents a menu item, and nested <ul> elements create submenus. You can use any HTML elements within your <li> elements to create your menu items (e.g., links, icons, text).

<ul id="myMenu">
  <li>
    <a href="#">Item 1</a>
  </li>
  <li>
    <a href="#">Item 2</a>
    <ul>
      <li><a href="#">Subitem 2.1</a></li>
      <li><a href="#">Subitem 2.2</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Item 3</a>
  </li>
</ul>

This structure is crucial for MetisMenu to correctly identify and handle the menu hierarchy.

Configuration Options

MetisMenu offers several configuration options to customize its behavior. These options are passed as a JavaScript object to the metisMenu() function.

Example usage:

$('#myMenu').metisMenu({
  toggle: false,
  preventDefault: false
});

Default Styles

MetisMenu includes default CSS styles to provide a basic visual appearance. These styles are included in the metisMenu.css file. You can override these styles or create entirely custom styles using your own CSS to match your project’s design. The default styles provide a clean, functional appearance, but you’ll likely want to customize them to integrate seamlessly with your application’s overall look and feel. Inspect the provided CSS file to understand the default styling.

Configuration Options

toggle Option

This boolean option controls how submenus behave when a parent menu item is clicked.

preventDefault Option

This boolean option determines whether the default link behavior (navigation to the href URL) is prevented when clicking a menu item with a submenu.

slideUpSpeed Option

This option controls the animation speed (in milliseconds) when a submenu collapses. Use a numeric value representing milliseconds. Default is 200. For no animation, set it to 0.

slideDownSpeed Option

This option controls the animation speed (in milliseconds) when a submenu expands. Use a numeric value representing milliseconds. Default is 200. For no animation, set it to 0.

triggerElement Option

This option specifies the element within the <li> item that triggers the submenu’s expansion/collapse. By default, it targets the <a> element. You can use a CSS selector to target a different element, if needed. For instance, if you want to trigger the menu using a specific class: triggerElement: '.my-custom-trigger'

expand Option

This method allows programmatic expansion of a specific menu item. You can call it using the following syntax after initialization:

$('#myMenu').metisMenu('expand', '#myMenuItem'); //Replace with your menu item selector.

This will expand the menu item with the given selector.

collapse Option

This method allows programmatic collapse of a specific menu item. Similar to expand, call it after initialization:

$('#myMenu').metisMenu('collapse', '#myMenuItem'); // Replace with your menu item selector.

This will collapse the menu item with the given selector.

activeClass Option

This option allows you to customize the CSS class applied to active menu items. By default it uses ‘active’. Change this to a different string value if needed, for example: activeClass: 'is-active'

onTransitionEnd Option

This option allows you to specify a callback function that will be executed when a submenu’s transition (slide up or down) completes. The callback function receives the target element as an argument. Useful for additional actions after the animation is finished.

$('#myMenu').metisMenu({
  onTransitionEnd: function(element) {
    console.log('Transition ended on:', element);
  }
});

Customizing the Menu

While MetisMenu provides default styles, significant customization is achieved through CSS. Inspect the default CSS to understand its structure and modify styles as needed. You can target specific classes applied by MetisMenu to customize appearances and behaviors without modifying the plugin’s core functionality.

Using Data Attributes

MetisMenu supports using data attributes on list items for finer control. While not exhaustive, here are some examples:

Example:

<li data-toggle="collapse">
  <a href="#">Item that won't collapse</a>
  <ul>...</ul>
</li>

Remember to consult the latest MetisMenu documentation for the most up-to-date information on available data attributes and configuration options.

Advanced Usage

Nested Menus

MetisMenu inherently supports nested menus of arbitrary depth. Simply nest <ul> elements within your <li> elements to create hierarchical menus. The plugin automatically handles the collapsing and expanding of nested submenus. Ensure your HTML structure is well-formed and correctly nested to achieve the desired hierarchy.

Accordion Menus

To create an accordion-style menu (where only one submenu is open at a time), you’ll need to manage this behavior yourself using JavaScript. You can listen for the shown.metisMenu and hidden.metisMenu events (see Event Handling below) to detect when submenus are opened and closed and then programmatically close other open submenus. This would typically involve traversing the DOM to find other open submenus and closing them using the collapse method.

Programmatic Control

MetisMenu provides methods for programmatic control over the menu’s state:

These methods are called on the jQuery object representing your menu after initialization:

$('#myMenu').metisMenu('expand', '#menuItemToExpand');
$('#myMenu').metisMenu('collapse', '.submenu');
$('#myMenu').metisMenu('destroy');

Event Handling

MetisMenu triggers several events that you can listen for using jQuery’s on() method:

You can use these events to implement custom actions, such as updating the UI or performing other tasks in response to menu state changes:

$('#myMenu').on('shown.metisMenu', function(event, data) {
  console.log('Submenu shown:', data.target);
});

$('#myMenu').on('hidden.metisMenu', function(event, data) {
  console.log('Submenu hidden:', data.target);
});

The data object in event handlers contains a target property referring to the element affected by the event.

Customizing Styles

MetisMenu’s visual appearance is highly customizable through CSS. You can override the default styles or create your own entirely. Inspect the provided CSS to identify the classes applied to different elements of the menu, and then target those classes in your custom CSS to create the desired look and feel. Consider using a CSS preprocessor (like Sass or Less) for more organized and maintainable styles.

Integration with Other Libraries

MetisMenu is designed to be compatible with other JavaScript libraries. Ensure that any conflicts are properly resolved, potentially adjusting initialization order or using techniques like namespaces to avoid naming collisions. Testing is crucial to ensure smooth integration.

Accessibility

MetisMenu is designed with accessibility in mind, but proper implementation depends on how you integrate it into your application. Ensure that you use appropriate ARIA attributes (like aria-expanded on menu items) to provide semantic information for assistive technologies. Proper keyboard navigation should also be implemented, considering how users would navigate the menu using only the keyboard. Thorough testing with assistive technologies is essential to confirm accessibility compliance.

API Reference

Methods

MetisMenu provides several methods to control its behavior programmatically. These methods are called on the jQuery object representing the initialized menu element.

Example Usage:

// Initialize the menu
$('#myMenu').metisMenu();

// Expand a submenu after initialization
$('#myMenu').metisMenu('expand', '#submenu1');

// Collapse a submenu
$('#myMenu').metisMenu('collapse', '.my-submenu-class');

// Remove MetisMenu functionality
$('#myMenu').metisMenu('destroy');

Events

MetisMenu triggers custom events that can be used to respond to changes in the menu’s state. These events are triggered on the menu element itself. Use jQuery’s .on() method to attach event handlers.

Example Usage:

$('#myMenu').on('shown.metisMenu', function(event, data) {
  console.log('Submenu shown:', data.target);
  // Add custom logic here, e.g., update UI elements
});

$('#myMenu').on('hidden.metisMenu', function(event, data) {
  console.log('Submenu hidden:', data.target);
  // Add custom logic here
});

These events provide a mechanism to integrate MetisMenu with other parts of your application, allowing for dynamic updates and custom interactions based on menu state changes. Remember that the data object passed to the event handler provides context about the specific menu item involved in the event.

Troubleshooting

Common Issues

Debugging Tips

By systematically checking these points and using the debugging tools provided by your browser, you can effectively identify and resolve most issues you encounter when using MetisMenu. If a problem persists, providing a minimal, reproducible example of your code (including HTML, CSS, and JavaScript) will greatly assist in getting help from the community or the MetisMenu maintainers.

Examples

These examples demonstrate different usage scenarios of MetisMenu. Remember to include the necessary jQuery and MetisMenu files (JavaScript and CSS) in your HTML before implementing these examples.

Simple Menu

This example shows a basic, single-level menu.

<ul id="simpleMenu">
  <li><a href="#">Item 1</a></li>
  <li><a href="#">Item 2</a></li>
  <li><a href="#">Item 3</a></li>
</ul>

<script>
  $(document).ready(function() {
    $('#simpleMenu').metisMenu();
  });
</script>

This will create a simple, unordered list that is styled by MetisMenu’s default CSS.

Nested Menu

This example demonstrates a multi-level, nested menu.

<ul id="nestedMenu">
  <li>
    <a href="#">Item 1</a>
  </li>
  <li>
    <a href="#">Item 2</a>
    <ul>
      <li><a href="#">Subitem 2.1</a></li>
      <li><a href="#">Subitem 2.2</a></li>
      <li>
        <a href="#">Subitem 2.3</a>
        <ul>
          <li><a href="#">Sub-subitem 2.3.1</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="#">Item 3</a></li>
</ul>

<script>
  $(document).ready(function() {
    $('#nestedMenu').metisMenu();
  });
</script>

This creates a menu with nested submenus. MetisMenu handles the collapsing and expanding behavior automatically.

Accordion Menu

Creating an accordion menu (only one submenu open at a time) requires custom JavaScript to manage the state. This example provides a basic implementation. More sophisticated approaches may be needed depending on complexity.

<ul id="accordionMenu">
  <li>
    <a href="#">Item 1</a>
    <ul>
      <li><a href="#">Subitem 1.1</a></li>
    </ul>
  </li>
  <li>
    <a href="#">Item 2</a>
    <ul>
      <li><a href="#">Subitem 2.1</a></li>
    </ul>
  </li>
</ul>

<script>
  $(document).ready(function() {
    $('#accordionMenu').metisMenu();
    let isOpen = false;
    $('#accordionMenu').on('shown.metisMenu', function(event, data){
        if(isOpen){
            $('#accordionMenu li ul').not(data.target).slideUp();
        }
        isOpen = true;
    });
  });
</script>

This example uses the shown.metisMenu event to close other open submenus when a new one is opened.

Custom Styling

Customizing the appearance involves creating your own CSS rules to override or extend MetisMenu’s default styles. This example demonstrates modifying the background color of menu items:

/* Your custom CSS */
#myCustomMenu li a {
  background-color: #f0f0f0; /* Example: Light gray background */
}

#myCustomMenu li ul {
  background-color: #e0e0e0; /* Example: Slightly darker gray for submenus */
}
<ul id="myCustomMenu">
  <li><a href="#">Item 1</a></li>
  <li><a href="#">Item 2</a>
    <ul>
        <li><a href="#">Subitem</a></li>
    </ul>
  </li>
</ul>

<script>
  $(document).ready(function() {
    $('#myCustomMenu').metisMenu();
  });
</script>

Remember to include your custom CSS file in your HTML. This demonstrates a basic style change; you can customize any aspect of the menu’s visual presentation using CSS. Inspect the default MetisMenu CSS to see the classes you can target.

Contributing

We welcome contributions to MetisMenu! Whether you’re reporting bugs, suggesting features, or submitting code changes, your help is valuable. Here’s how you can contribute:

Reporting Issues

If you encounter a bug or have a feature request, please report it on the project’s issue tracker (replace with actual link to issue tracker). When reporting an issue, please provide the following information:

The more information you provide, the easier it will be to diagnose and fix the problem.

Submitting Pull Requests

If you’d like to contribute code changes (bug fixes, new features, etc.), follow these steps:

  1. Fork the repository: Create a fork of the MetisMenu repository on GitHub.

  2. Create a new branch: Create a new branch for your changes. Use a descriptive branch name that clearly indicates the purpose of your changes (e.g., fix-bug-123, feature-new-option).

  3. Make your changes: Make your code changes, ensuring that they adhere to the project’s coding style and conventions. Thoroughly test your changes to ensure they work correctly and don’t introduce new bugs.

  4. Commit your changes: Commit your changes with clear and concise commit messages that explain what you’ve done.

  5. Push your branch: Push your branch to your forked repository.

  6. Create a pull request: Create a pull request on the main MetisMenu repository, linking to your branch. Provide a clear description of your changes in the pull request description.

  7. Address feedback: Be prepared to address any feedback or suggestions from the maintainers. They may request changes to your code before merging it into the main project.

Before submitting a pull request, please ensure that your code passes all tests (if applicable) and adheres to the project’s coding style guidelines. A well-written pull request with clear explanations significantly increases the likelihood of your contribution being accepted.