To create a collapsible or accordion-style menu with jQuery, you can follow these steps:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<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>
.menu .submenu {
display: none;
}
.menu li {
cursor: pointer;
padding: 5px;
background-color: #f2f2f2;
}
$(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.
That's it! You have now created a collapsible or accordion-style menu using jQuery.