How to create a collapsible or accordion-style menu with jQuery?

To create a collapsible or accordion-style menu with jQuery, you can follow these steps:

  1. Include the jQuery library in your HTML document by adding the following script tag:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  1. Create an HTML structure for your menu with nested list items. Each parent list item should have a corresponding child list item(s) for the collapsible/accordion effect. For example:
<ul class="menu"> <li>Parent 1 <ul class="submenu"> <li>Child 1</li> <li>Child 2</li> </ul> </li> <li>Parent 2 <ul class="submenu"> <li>Child 3</li> <li>Child 4</li> </ul> </li> </ul>
  1. Add CSS styles to hide the child list items by default and style the menu as desired. For example:
.menu .submenu { display: none; } .menu li { cursor: pointer; padding: 5px; background-color: #f2f2f2; }
  1. Use JavaScript/jQuery to handle the click event on the parent list items and toggle the visibility of the corresponding child list item(s). Add the following script:
$(document).ready(function() { $('.menu li').click(function() { $(this).children('.submenu').slideToggle(); }); });

This code waits for the document to be ready, selects all list items within elements with a class of 'menu', and attaches a click event handler to them. When a list item is clicked, it toggles the visibility of its child element with the class 'submenu' using the 'slideToggle' method.

  1. You can further customize the accordion-style menu by adding additional CSS styles and jQuery methods to handle the open/close state of the menu items.

That's it! You have now created a collapsible or accordion-style menu using jQuery.