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.
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.
MetisMenu can be installed using several methods:
Download: Download the latest release from https://github.com/onokumus/metismenu. Extract the contents and include the metisMenu.js
and metisMenu.css
files in your project.
CDN: Include the MetisMenu files directly from a CDN. Several CDNs may host MetisMenu; refer to the project’s website for the most up-to-date links.
<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.
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.
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.
MetisMenu offers several configuration options to customize its behavior. These options are passed as a JavaScript object to the metisMenu()
function.
toggle
: (Boolean) If true
, submenus will toggle open and closed on click. If false
, submenus will only expand on click. Defaults to true
.preventDefault
: (Boolean) If true
, prevents default link behavior (navigation) when clicking on a menu item with a submenu. Defaults to true
.doubleTapToGo
: (Boolean) If true
, requires a double tap on a menu item to trigger navigation if it has a submenu. Useful to avoid accidental submenu toggling on touch devices. Defaults to false
.Example usage:
$('#myMenu').metisMenu({
toggle: false,
preventDefault: false
; })
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.
toggle
OptionThis boolean option controls how submenus behave when a parent menu item is clicked.
true
(default): Submenus will toggle – opening if closed and closing if open.false
: Submenus will only open when clicked; clicking a already-open submenu will not close it.preventDefault
OptionThis boolean option determines whether the default link behavior (navigation to the href
URL) is prevented when clicking a menu item with a submenu.
true
(default): Prevents the default link behavior. Useful to avoid accidental navigation when intending to open a submenu.false
: Allows the default link behavior, even if the item has a submenu. The submenu will still open/close as configured.slideUpSpeed
OptionThis 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
OptionThis 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
OptionThis 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
OptionThis 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
OptionThis 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
OptionThis 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
OptionThis 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);
}; })
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.
MetisMenu supports using data attributes on list items for finer control. While not exhaustive, here are some examples:
data-toggle="collapse"
: This can be used to override the default behavior of toggle
option for individual items. Setting this to collapse
will prevent a menu item from collapsing even if toggle
is true
.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.
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.
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.
MetisMenu provides methods for programmatic control over the menu’s state:
expand(selector)
: Expands the menu item matching the given selector.collapse(selector)
: Collapses the menu item matching the given selector.destroy()
: Removes MetisMenu functionality from the element.These methods are called on the jQuery object representing your menu after initialization:
$('#myMenu').metisMenu('expand', '#menuItemToExpand');
$('#myMenu').metisMenu('collapse', '.submenu');
$('#myMenu').metisMenu('destroy');
MetisMenu triggers several events that you can listen for using jQuery’s on()
method:
shown.metisMenu
: Triggered when a submenu is shown (expanded).hidden.metisMenu
: Triggered when a submenu is hidden (collapsed).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.
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.
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.
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.
MetisMenu provides several methods to control its behavior programmatically. These methods are called on the jQuery object representing the initialized menu element.
metisMenu(options)
: Initializes the plugin. options
is an object containing configuration options (see Configuration Options section). This is the method used for initial setup.
metisMenu('expand', selector)
: Expands the submenu matching the given selector
. The selector
should be a valid CSS selector targeting the <li>
element containing the submenu.
metisMenu('collapse', selector)
: Collapses the submenu matching the given selector
. Similar to expand
, the selector
targets the relevant <li>
.
metisMenu('destroy')
: Removes MetisMenu functionality from the element, reverting it to its original state before initialization. This removes any added classes and event handlers.
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');
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.
shown.metisMenu
: This event is fired after a submenu has been expanded (shown). The event object contains a target
property that references the expanded submenu element.
hidden.metisMenu
: This event is fired after a submenu has been collapsed (hidden). The event object also contains a target
property referencing the collapsed submenu element.
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.
Menu not initializing: Double-check that you’ve included jQuery and the MetisMenu JavaScript and CSS files correctly. Ensure the script including MetisMenu is placed after the jQuery inclusion and that the script is executed after the DOM is fully loaded (e.g., within a $(document).ready()
function). Verify that there are no JavaScript errors in your browser’s console. Incorrect selectors for the menu element in your initialization call ($('#myMenu')
in the examples) are a frequent cause.
Submenus not expanding/collapsing: Make sure your HTML structure is valid, with properly nested <ul>
and <li>
elements. Inspect your menu’s HTML in the browser’s developer tools to ensure the structure is as expected. Check for any CSS conflicts that might be overriding MetisMenu’s styles. Inspect the browser’s developer console for JavaScript errors related to MetisMenu.
Incorrect animation: If submenus are not animating smoothly or at all, check the slideUpSpeed
and slideDownSpeed
configuration options. A value of 0
disables animation. Ensure that there are no CSS rules conflicting with the animation.
Conflicts with other libraries: If you’re using other JavaScript libraries that manipulate the DOM, conflicts might occur. Try adjusting the order of script inclusions or using techniques like namespaces to avoid naming clashes. Check your browser’s developer console for any errors related to JavaScript conflicts.
Accessibility issues: Ensure you’ve included appropriate ARIA attributes (like aria-expanded
) and that keyboard navigation works as expected. Test your menu thoroughly with assistive technologies like screen readers.
Browser Developer Tools: Use your browser’s developer tools (usually accessed by pressing F12) to inspect your HTML, CSS, and JavaScript. This allows you to check for errors in your code, inspect the DOM structure, and see if CSS styles are applied correctly. The console will display any JavaScript errors, which are crucial for identifying problems.
Simplify Your Markup: Create a minimal, isolated example of your menu structure to rule out conflicts with other parts of your code. This allows you to focus on the core MetisMenu functionality.
Check the Console: The browser’s JavaScript console will often show errors that can help pinpoint the source of issues. Pay close attention to any errors or warnings related to MetisMenu.
Inspect Network Requests: Ensure that the MetisMenu files are correctly loaded. Use your browser’s developer tools to check the network tab, verifying that the .js
and .css
files are being downloaded and have the correct content-type.
Step-Through with a Debugger: If the problem is difficult to isolate, use your browser’s debugger to step through the MetisMenu JavaScript code line by line. This allows you to examine variables and see exactly what is happening at each stage.
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.
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.
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.
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.
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();
}= true;
isOpen ;
});
})</script>
This example uses the shown.metisMenu
event to close other open submenus when a new one is opened.
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.
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:
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:
Clear and concise description: Explain the problem clearly and concisely. What were you trying to do? What happened instead? Include relevant error messages.
MetisMenu version: Specify the version of MetisMenu you are using.
Browser and operating system: Note the browser and operating system you’re using. This information can help identify browser-specific issues.
Reproducible example: If possible, provide a minimal, reproducible example that demonstrates the issue. This can significantly speed up the debugging process. A JSFiddle or CodePen link is ideal.
Relevant code snippets: Include any relevant code snippets from your HTML, CSS, and JavaScript files.
The more information you provide, the easier it will be to diagnose and fix the problem.
If you’d like to contribute code changes (bug fixes, new features, etc.), follow these steps:
Fork the repository: Create a fork of the MetisMenu repository on GitHub.
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
).
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.
Commit your changes: Commit your changes with clear and concise commit messages that explain what you’ve done.
Push your branch: Push your branch to your forked repository.
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.
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.